mercredi 25 mai 2016

smart_ptr to attribute of class segfault

I am wondering if this example would cause a segfault, because the dtor of the object is called an I am still holding a shared_ptr to an attribute of the object.

struct foo{
    std::shared_ptr<std::string> const bar = std::make_shared<std::string>("foo");

    foo() {std::cout << "CTOR!" << std::endl;} 

    ~foo(){std::cout << "DTOR!" << std::endl;}
};
int main() {
    std::shared_ptr<std::string> ptr;
    {
        std::shared_ptr<foo> foo_ptr = std::make_shared<foo>();
        ptr = foo_ptr->bar;
    }
    std::cout << *ptr << std::endl;


    return 0;
}

Aucun commentaire:

Enregistrer un commentaire