如何返回可以更改的会员? [英] How to return member that can be changed?
问题描述
多线程环境。 Foo的内容可以是多线程。
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_;
};
呼叫者:
A a = foo.getA();
在另一个问题中,我问某人告诉我
如果您返回const&可以保证变量的生命周期会延长到引用的生命周期
,所以根据此,我不需要复制值,即使在调用后立即对foo调用setA也是安全的到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_;}
,但是编译器仍然警告我,我已经引用了local变量。我不明白为什么,因为据我了解(cpp的新手),返回值是foo.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不担心a_内容的更改。(_ a.age = 4)。我担心调用set,并且调用方中的 a将是非法的
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
推荐答案
您需要更加小心你听。如果将临时对象立即绑定到const-reference,则唯一延长其寿命的时间。例如,像这样:
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:
Foo bar() { return Foo(); }
int main()
{
Foo const & f = bar();
/* stuff */
} // the object referred to by f is extended till here
您的情况并非如此。特别是返回const-reference 不会创建临时对象,因此这里没有任何东西可以延长寿命。特别是,以下内容绝对是 错误:
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:
A const & bar() { Foo x; return x.getA(); }
int main()
{
A const & a = bar(); // dangling reference; object dies upon return from Foo::getA()
}
这篇关于如何返回可以更改的会员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!