Search code examples
c++referencesmart-pointersdestroy

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);
}
  • Is a the owner of the object?
  • When 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?


Solution

  • 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.