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();
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.