As I know, C++ only have function overload base on the parameter or implicate object parameter. But I find there are two operator[] for vector. And it will select the correct function in following code:
std::vector<int> v;
v[0] = 1; // This will select the non-const version.
return &v[0]; // This will select the const version.
Can anyone explain how this happen?
reference operator[] (size_type n);
const_reference operator[] (size_type n) const;
------Edit 1------
I think it will select the const version, because following cc file cannot compile with clang++ and g++ with following error. Doesn't understand following error. Can anyone explain more?
error: cannot initialize return object of type 'char *' with an rvalue of type 'const value_type *' (aka 'const char *') return data_.size() == 0 ? NULL : (&data_[0]);
#include <assert.h>
#include <deque>
#include <vector>
#include <map>
class X
{
public:
X() {
}
virtual ~X() {
}
char* data() const {
return data_.size() == 0 ? NULL : (&data_[0]);
}
size_t size() const {
return data_.size();
}
private:
std::vector<char> data_;
};
&v[0]
selects the const version? – emlaiconst
version because thedata
function is markedconst
. – TartanLlama