How to return member that can be changed?

前端 未结 1 817
北恋
北恋 2020-12-22 08:11

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         


        
相关标签:
1条回答
  • 2020-12-22 09:07

    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
    

    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()
    }
    
    0 讨论(0)
提交回复
热议问题