Multi thread enviroment . The content of Foo can be multi thread.
class Foo
{
public:
const A & getA() {return a_;} //has guard
void setA(A newA){a_ = newA;} //has guard
private:
A a_;
};
caller:
A a = foo.getA();
in another question that i asked someone told me that
If you return const& it’s guaranteed that life time of variable will be prolonged to lifetime of the reference
, so according to this i dont need to copy the value and i safe even if call to setA on foo done right after i call to getA, but a lot of argument against it was araised , so i feel that this is not correct.
I want to be on the safe side so i change the signature to be :
A & getA() {return a_;}
but the compiler still give me warning that i have reference to local variable. i dont understand why, because as far as i understand (new to cpp) the return value is a copy of foo.a, so what the problem with this?
i am not worried about change of a_ content.(_a.age =4) . i worry about call to set and that my ‘a’ in the caller will be illegal
You need to be more careful who you listen to. The only time the lifetime of something gets extended if a temporary object is bound immediately to a const-reference. For example, like so:
Your situation is nothing like that. In particular, returning a const-reference does not create a temporary object, so there’s nothing here who’s life gets prolonged. In particular, the following is definitely an error: