Sid Zhang
Sid Zhang

Reputation: 972

what is the best way to return a pointer to vector's data? const or non-const?

#include <vector>

using std::vector;

class A
{

public:
    A()
    {
        buf.push_back(65);
        buf.push_back(66);
        buf.push_back(67);
    }

    ~A(){}

    const char *  getA() const
    {
        // why never run here?
        return &buf[0];
    }

    const char * getA()
    {
        return &buf[0];
    }

    char *  getB() const
    {
        // why compile error?
        return &buf[0];
    }

    char * getB()
    {
        return &buf[0];
    }

private:
    vector<char> buf;
};

int main()
{
    A a;
    const char * pc = a.getA();
    const char * const cp = a.getA();
    char * p = a.getB();
}

two questions:

1> Why there is a compile error?

2> Why the

const char * getA() const

never be called?(In my mind, this one should be called firstly, because I won't change the object)

I have debuged into the vector class implementation and found the

reference operator[](size_type _Pos) const {...}

was called , not the

const_reference operator[](size_type _Pos) const{...}

one.

PS: I use VS2010.

Upvotes: 2

Views: 1910

Answers (4)

Jerrfey
Jerrfey

Reputation: 65

For your second question:cause of "A a" was not constant , const version will never been called !

Upvotes: 1

O.C.
O.C.

Reputation: 6819

I will answer your second question. Read this const correctness. It says that if you want your const overload to be called your object should be const too.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272517

Question 1

There is a compiler error because you've declared getB() as const. So therefore, buf is effectively const, so operator[] will return a const reference to the member element.

Question 2

That overload of getA() never gets called because a is not const, so the non-const overload takes priority. If you do:

const A *p = &a;
p->getA();

then the const overload would get called.

Upvotes: 6

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361472

In a const member function, every member of the class is const. That said, you cannot return non-const pointer from a const vector, hence the error in this code:

char* getB() const
{
    // why compile error?
    return &buf[0];
}

Since inside the function, buf becomes const vector<char>, and consquently &bug[0] becomes cont char*. So you need to make the return type as const char* to fix the compilation error.

Upvotes: 1

Related Questions