1

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();
Owen
  • 7,494
  • 10
  • 42
  • 52
duong_dajgja
  • 4,196
  • 1
  • 38
  • 65
  • Possible duplicate of [Differences between std::make\_unique and std::unique\_ptr](https://stackoverflow.com/questions/22571202/differences-between-stdmake-unique-and-stdunique-ptr) – Lanting Jan 02 '18 at 09:42

1 Answers1

4

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • I added some more lines to the example. According to your newly added comment, `p->do_something();` shouldn't be there? – duong_dajgja Jan 02 '18 at 07:28
  • @duong_dajgja As long as the `std::unique_ptr` object still exists, then you *can* use the raw pointer like you do. However, I strongly recommend against it. I also strongly recommend you *don't* do like you do with a raw non-owning pointer that you at a later point move ownership to a `std::unique_ptr`. Instead *start* with a `std::unique_ptr`. What you're doing is saying that the object pointed to by `p` is *owned* by the new `std::unique_ptr` object. – Some programmer dude Jan 02 '18 at 07:34