The increased lifetime of the object returned by the function

There is some obscure information for me about extending the lifetime of an object returned from a function and bound to an rvalue / const lvalue reference. Information from here .

temporary binding to the return value of the function in the return statement does not apply: it is immediately destroyed at the end of the returned expression. Such a function always returns a dangling link.

If I understand correctly, the quote states that the lifetime of objects returned by return statements cannot extend. But the last sentence suggests that it applies only to functions that return links.
In GCC, from the code below, I get the following output:

struct Test
{
  Test() { std::cout << "creation\n"; }
  ~Test() { std::cout << "destruction\n"; }
};

Test f()
{
    return Test{};   
}

int main()
{
    std::cout << "before f call\n";
    Test && t = f();
    std::cout << "after f call\n";
}

before f call
creation
after f call
destruction

, , .
, ? ?

+6
2

, , .

, , , , , f() Test{}, f(). , t, . BTW , .

:

struct Test
{
  Test() { std::cout << "creation\n"; }
  ~Test() { std::cout << "destruction\n"; }
  Test(Test&&) { std::cout << "move\n"; }
};

copy elision, :

before f call
creation      // the temporary created inside f
move          // return object move-constructed
destruction   // the temporary destroyed
after f call
destruction   // the returned object destroyed

LIVE


, $15.2/6 [class.temporary]:

, , :

(6.1) , , .

(6.2) ; return.

(6.3) , . [:

struct S { int mi; const std::pair<int,int>& mp; };
S a { 1, {2,3} };
S* p = new S{ 1, {2,3} };   // Creates dangling reference

- ] [. . - ]

+6

GOTW

, . ++ , const ( ravlue) , , , ,

string f() { return "abc"; }

void g() {
const string& s = f();
  cout << s << endl;    // can we still use the "temporary" object?
}

, f(), . ( , . , .)

legalese, SO

, rvalue

0

Source: https://habr.com/ru/post/1016469/


All Articles