Search code examples
c++unique-ptrdangling-pointer

unique_ptr<int> dangling pointer


C++ code:

unique_ptr<int> a  = make_unique<int>(159);
  auto var = a.get(); // Edited a => a.get() sorry
  a.release();
  std::cout<<*var<<std::endl; // prints "159"

Is var dangling pointer after this code?


Solution

  • Your code is perfectly valid. a.release() detaches the dynamically allocated object from the unique pointer, so a no longer owns the integer, but nothing is being deleted.

    You will have a memory leak unless you don't eventually call delete var, though.