Reputation: 2826
if I have something along the lines of:
auto foo=Foo(Bar())
where Foo's constructor takes a const reference to Bar, is there some way to ensure that Bar's destructor will not get called before the destructor on foo at the end of the scope of foo, so that the reference to Bar will still be valid even in foo's destructor?
Upvotes: 2
Views: 65
Reputation: 66912
The relative order of the destructors is guaranteed.
auto foo=Foo(Bar());
Since Bar()
is a temporary, then it is guaranteed to be destructed at the end of the expression: aka the semicolon. You are absolutely guaranteed that the Bar
is destroyed before foo
.
There is no way to extend the lifetime of this temporary, you'll have to make a copy of it (potentially by moving it). Alternatively:
{
Bar b;
auto foo=Foo(b);
}
Since the objects in a single scope are destroyed in the opposite order they're constructed, then since these are in the same scope, b
will be destroyed after foo
is destroyed.
Upvotes: 6