Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ lifetieme extension with different parentheses [duplicate]

I'm trying to understand lifetime extension guarantees in C++. Can someone explain why the usage of different types of parentheses below yields differing results in terms of when the temporary object destructor is invoked?

#include <iostream>
struct X  {
    X() { 
        std::cout << __PRETTY_FUNCTION__ <<"\n";
    }
    ~X() {
        std::cout << __PRETTY_FUNCTION__ <<"\n";
    }
};

struct Y {
    X &&y;
};
int main() { 
    Y y1(X{});    
    std::cout << "Here1\n";
    Y y2{X{}};
    std::cout << "Here2\n";
}

Output

X::X()
X::~X()
Here1
X::X()
Here2
X::~X()
like image 487
user3882729 Avatar asked Jan 02 '26 00:01

user3882729


1 Answers

Since C++20:

There are following exceptions to this lifetime rule:

  • ...

  • a temporary bound to a reference in a reference element of an aggregate initialized using direct-initialization syntax (parentheses) exists until the end of the full expression containing the initializer, as opposed to list-initialization syntax {braces}.

    struct A
    {
        int&& r;
    };
    
    A a1{7}; // OK, lifetime is extended
    A a2(7); // well-formed, but dangling reference
    

That means for Y y2{X{}};, the lifetime of temporary will be extended as y2 (and its member); while for Y y1(X{}); it won't, the temporary will be destroyed after full expression immediately.

like image 114
songyuanyao Avatar answered Jan 03 '26 14:01

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!