samedi 30 septembre 2017

Creating shared pointer from this pointer

Below code gives segmentation fault as expected.

struct B{
    shared_ptr<B> createShared(){ return shared_ptr<B>(this);}
};

int main()
{
    shared_ptr<B> p1 = make_shared<B>();
    shared_ptr<B> p2 = p1->createShared();
    return 0;
}

but when I change the code

shared_ptr<B> p1 = make_shared<B>();
        to
shared_ptr<B> p1(new B);

program compiles as runs without any crash.

Can someone explain me what exactly is causing the change in behavior between these two cases.

Note:- I know that it is not the right way to create the shared pointer from this pointer, what I am looking for is the reason for change in behavior. Compiler I used is clang++-3.8 and g++-5.4.

Aucun commentaire:

Enregistrer un commentaire