Reputation: 2489
Here is a program that represents my conceptual problem:
int main()
{
unique_ptr<int> a = make_unique(5);
{
unique_ptr<int>& b = a;
}
printf("%d",*a);
}
a
the owner of the object?a
goes out of scope, does the value of somepointer get destroyed?By running the above code I see it doesn't but I don't understand why. What exactly happens in the assignment?
Upvotes: 2
Views: 519
Reputation: 15182
The assignment to b
is simply a reference, it has no bearing on the object lifetime of a
. Imagine instead that you had passed a to a function taking a unique_ptr<int> &
, you wouldn't expect the reference to alter the lifetime of a in that case, why would you do so here?
Upvotes: 3
Reputation: 666
a
remains the owner of the object this entire time.
In C++, placing &
before a variable name creates a reference, which is like an implicit pointer. Since you've declared b
as a reference, there is only ever one unique_pointer
in this code. a
is the unique_pointer
itself, and the reference b
points to that pointer.
This is the reason the unique_pointer
is not destroyed when the block containing b
is exited; b
never owned the resource because b
was never a unique_pointer
to begin with, only a reference to one.
See learncpp for a full lesson on references.
Upvotes: 3