Could you help me with this problem
struct b {
Something bSomething;
const Something & MySomething() const {
return bSomething;
}
};
开发者_JS百科I want to know why the method return type is const Something& I think it might just be simply Something as in
Something MySomething() const {
return bSomething;
}
and
Something MySomething() {
return bSomething;
}
Thank you
You cannot return a non-constant reference to a member in a constant function. The usual two overloads for direct member accessors are like this:
const Foo & foo() const { return m_foo; }
Foo & foo() { return m_foo; }
Inside a constant function, the type of this
is const T *
(where T
is your class). Thinking of your class as a dumb C struct for a minute, you are returning *this->m_foo
, but that's constant when this
is a pointer-to-constant, so you cannot make a non-constant reference to that.
Returning by value is fine because you invoke the copy constructor of Foo
, which has signature Foo(const Foo&)
-- so it can copy from constant references:
Foo copy_foo() const { return m_foo; } // calls Foo(*this->m_foo)
That mean that the value returned is not editable (first const) and that calling this method will not alter the struct instance in any way (second const)
The second const is very interesting because you can use it on const values too. If you have a situation where a method return a const mytype&, you can call methods only if they are declared const (at the end like the one before). Otherwise you aren't allowed to do that.
If you leave out the first const, you will have a value that is editable. However because you are returning it through a const method (something that doesn't alter the struct, but returning a non-const value that is inside the class is a possibility to change the value of the instance), it's not valid a valid operation
精彩评论