Let's say I have a class which is a child class of enable_shared_from_this. The documentation of this base class says there should be a shared pointer which owns this class before calling shared_from_this. Is it safe to allocate the class with new and call shared_from_this to manage the object?
No, it's not safe. You should only call shared_from_this
if the object is managed by a shared_ptr
, not allocated via new
(without an associated shared_ptr
). For example this code
struct Test: std::enable_shared_from_this<Test> {
std::shared_ptr<Test> getptr() {
return shared_from_this();
}
};
Test *test = new Test;
std::shared_ptr<Test> test2 = test->getptr();
will throw std::bad_weak_ptr
(at least when using libstdc++
). But this is OK:
std::shared_ptr<Test> test(new Test);
std::shared_ptr<Test> test2 = test->getptr();