'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 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Some programmer dude