DsCpp
DsCpp

Reputation: 2489

Hold a unique pointer reference to a unique pointer reference

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);
}

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

Answers (2)

SoronelHaetir
SoronelHaetir

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

Qwertycrackers
Qwertycrackers

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

Related Questions