Search code examples
c++11smart-pointersunique-ptr

Is it safe to init a std::unique_ptr from a local raw pointer?


I know it's unwise to do so with a std::shared_ptr. But what about std::unique_ptr? E.g. :

class A {
 public:
  void do_something() { }
};

std::vector<std::unique_ptr<A> > uq_ptrs_;
auto p = new A();
uq_ptrs_.push_back(std::unique_ptr<A>(p));
p->do_something();

Solution

  • As long as you don't manually delete the object after creating the std::unique_ptr (or std::shared_ptr!) object then it's fine.

    You should also avoid dereferencing the pointer p once you asked the std::unique_ptr (or std::shared_ptr) to take ownership of it. Instead use the smart pointer object.