A structure having a strange return type

Could you help me with this problem?

struct b { Something bSomething; const Something & MySomething() const { return bSomething; } }; 

I want to know why the return type of the method is const Something & I think it might just be something like

  Something MySomething() const { return bSomething; } 

and

 Something MySomething() { return bSomething; } 

thanks

+4
source share
2 answers

You cannot return a permalink to an element in a constant function. The usual two overloads for direct access to access elements are:

 const Foo & foo() const { return m_foo; } Foo & foo() { return m_foo; } 

Inside a constant function, this is equal to const T * (where T is your class). Thinking of your class as a dumb C structure for a minute, you return *this->m_foo , but this constant, when this is a pointer to a constant, so you cannot refer to this constant.

The return by value is accurate because you call the copy constructor Foo , which has the signature Foo(const Foo&) - so it can copy from permalinks:

 Foo copy_foo() const { return m_foo; } // calls Foo(*this->m_foo) 
+3
source

This means that the return value is not editable (first const) and that calling this method will not in any way modify the instance of the structure (second constant)

The second constant is very interesting, because you can use it for const values ​​as well. If you have a situation where the method returns const mytype &, you can only call methods if they are declared const (at the end, as before). Otherwise, you are not allowed to do this.

If you leave the first const, you will have a value that is editable. However, due to the fact that you are returning it using the const method (something that does not change the structure, but returns a non-constant value inside the class , the ability to change the value of the instance), this is an invalid valid operation

+2
source

All Articles