c++ - Try to understand std::enable_shared_from_this<T> but cause a bad_weak_ptr using it -
i try understand behavior of std::enable_shared_from_this class, cant understand it. i've write simple program test different situations.
question
can explain me behavior of following code, because can't explain observed result.
thanks help.
code
#include <iostream> #include <memory> struct c : std::enable_shared_from_this<c> { }; int main () { {//test 1 std::shared_ptr<c> foo, bar; foo = std::make_shared<c>(); bar = foo->shared_from_this(); //ok std::cout<<"shared_ptr : ok"<<std::endl; } {//test 2 std::shared_ptr<c> foo = std::shared_ptr<c>(new c); std::shared_ptr<c> bar; bar = foo->shared_from_this(); //ok std::cout<<"shared_ptr + new : ok"<<std::endl; } {//test 3 c* foo = new c; std::shared_ptr<c> bar; bar = foo->shared_from_this(); //throw std::bad_weak_ptr std::cout<<"new : ok"<<std::endl; } {//test 4 (should make invalid free of that) c foo; std::shared_ptr<c> bar; bar = foo.shared_from_this();//throw std::bad_weak_ptr std::cout<<"local : ok"<<std::endl; } return 0; }
and here output:
shared_ptr : ok shared_ptr + new : ok terminate called after throwing instance of 'std::bad_weak_ptr' what(): bad_weak_ptr
build informations
- system : windows 7 x64
- compiler : mingw 4.9.2 x64
the contract enable_shared_from_this
provide shared_ptr
when call shared_from_this()
if object managed shared_ptr
. cannot create shared_ptr
if not being managed.
you figured out in last test case why bad idea allow shared_from_this()
create shared pointer you...
Comments
Post a Comment