多线程环境。 Foo的内容可以是多线程。

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();


在另一个问题中,我问有人告诉我
If you return const& it's guaranteed that life time of variable will be prolonged to lifetime of the reference
,所以根据此我不需要复制值,即使我在调用getA之后立即在foo上对setA进行调用也很安全,但是引发了很多反对它的争论,所以我觉得这是不正确的。

为了安全起见,我将签名更改为:

A & getA() {return a_;}


但是编译器仍然警告我已引用局部变量。我不明白为什么,因为据我了解(cpp的新手),返回值是foo.a的副本,那么这是什么问题呢?

我不担心a_ content的更改。(_ a.age = 4)。我担心呼叫设置,并且呼叫者中的“ a”将是非法的

最佳答案

您需要更加小心听谁的声音。如果将临时对象立即绑定到const引用,则仅延长某个对象的生存期。例如,如下所示:

Foo bar() { return Foo(); }

int main()
{
    Foo const & f = bar();

    /* stuff */

} // the object referred to by f is extended till here


你的情况不是那样。特别是,返回const引用不会创建临时对象,因此这里没有任何对象可以延长寿命。特别是以下绝对是错误:

A const & bar() { Foo x; return x.getA(); }

int main()
{
    A const & a = bar(); // dangling reference; object dies upon return from Foo::getA()
}

关于c++ - 如何返回可以更改的成员(member)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11744265/

10-13 09:19
查看更多