0
votes

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_;
};
2
Both select the non const version.Jarod42
Why do you think &v[0] selects the const version?emlai
Your edit uses the const version because the data function is marked const.TartanLlama
Ugh that is a completely different question, you should have asked the question that way in the first place.Shafik Yaghmour
@TartanLIama Oh, I see. Any reference from the standard to talk about this?ZijingWu

2 Answers

7
votes

Actually in both cases the non-const version is called. The time when the const version would be called would be if the vector was const.

std::vector<int> const v = {1,2,3};
int x = v[0];

In the above case, trying to invoke the non-const version would result in a compiler error

v[0] = 5;   // nope can't call non-const version, this is trying to mutate a const variable

Edit
Regarding your example, based on the signature of your function

char* data() const

you have declared that the method data is const, meaning that it shall not attempt to mutate any of the member variables. In other words, all member variables within a const function are treated as const. In the context of a const method, the variable is seen as

std::vector<char> const data_;
1
votes

Since v is a non-const vector the constversion is never called.