Smart_ptr for segfault class attribute

I am wondering if this example can call segfault, because the object dtor is called, I still save shared_ptr for the object attribute.

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;
}
+4
source share
2 answers

No, this will not happen. By assigning to std::shared_ptranother, you refuse his death.

This operation ptr = foo_ptr->bar;will increment the common pointer counter by one. This ensures that the dynamically allocated object in free storage remains alive.

Is this true even for the attributes of a destroyed object ?!

, . , , , ( , ...). , , -.


. :

std::shared_ptr<std::string> ptr;
{
    std::shared_ptr<foo> foo_ptr = std::make_shared<foo>();
    std::cout <<"References Count:" << foo_ptr->bar.use_count()<<"\n";
    ptr = foo_ptr->bar;
    std::cout <<"References Count:" << foo_ptr->bar.use_count()<<"\n";
}
std::cout <<"References Count:" << ptr.use_count()<<"\n";
std::cout << *ptr << std::endl;

:

CTOR!
References Count:1
References Count:2
DTOR!
References Count:1
foo

-

+4

. std::shared_ptr . , , ,

std::shared_ptr<std::string> ptr;

shared_ptr ptr, .

{
    std::shared_ptr<foo> foo_ptr = std::make_shared<foo>();
    ptr = foo_ptr->bar;
}

shared_ptr foo_ptr, foo foo, bar. bar ptr. , bar ( ), bar ptr . foo_ptr , , foo, bar. bar , . , . shared_ptr ( ), , , . ( - ptr = foo_ptr->bar), , ptr, .

std::cout << *ptr << std::endl;

ptr , , . , ptr , , , , . , std::shared_ptr , . . , , , .

+4

All Articles