c++ - Why can't a const method return a non-const reference? -



c++ - Why can't a const method return a non-const reference? -

why won't method getranks() below compile, , how can prepare gracefully?

all want define fellow member accessor method returns reference member. reference not const since might modify refers later. since fellow member method not modify object, declare const. compiler (clang, std=c++11) insists there "binding of reference" "drops qualifiers". i'm not dropping qualifiers, i? , if am, why:

struct teststruct{ vector<int> ranks; vector<int>& getranks()const{ homecoming ranks; } };

now, code compiles if alter homecoming statement cast away const:

return const_cast<vector<int>&>(ranks);

but "ranks" should not const in first place, don't see why need const_cast const away. don't know if it's safe this.

anyway, there cleaner write method? can explain why such simple common-sense method fails? want declare getranks() method "const" can phone call other const methods.

the thought behind const fellow member function should able phone call them on const objects. const functions can't modify object.

say have class

class { int data; void foo() const { } };

and on object , function call:

a const a; a.foo();

inside a::foo, this->data treated if type int const, not int. hence, not able modify this->data in a:foo().

coming example, type of this->ranks in getranks() considered const vector<int> , not vector<int>. since, auto conversion of const vector<int> vector<int>& not allowed, compiler complains when define function as:

vector<int>& getranks()const{ homecoming ranks; }

it won't complain if define function as:

const vector<int>& getranks()const{ homecoming ranks; }

since const vector<int> can auto converted const vector<int>&.

c++ c++11 reference const const-cast

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -