Suppose there is a class:

class A { public: private: std::string a; int b; bool c; UserClass d; }; 

A std::shared_ptr was created for it. When calling Sharedptr_classA.reset(); Will the destructor be called for UserClass and will memory be freed from other properties?

  • one
    Have you tried to insert cout into a destructor for verification? - rikimaru2013

2 answers 2

Yes, it will. The order is this - first, the destructor A called, then all the fields of the class will be called in the reverse order of their declaration.

    The destructor will be called if there is no longer any pointer to this object. shared_ptr works with a reference counter, and the destructor is called when this counter is reset.

    • Yes, it is assumed that this was the last shared_ptr. What about the other properties? - Dmitry
    • @Dmitry What do you mean? Do not really understand what properties you are talking about? Or are you about members like your a, b, c, d? Naturally, the class destructor causes destructors for all members. - Harry
    • std::string a; , int b; , bool c; - Dmitry
    • @Dmitry The destructor class causes destructors for all members. - Harry
    • @Dmitry Here's a little program for you - throw these and check if you are in doubt: class Quest { public: Quest() { cout << __func__ << endl; } ~Quest() { cout << __func__ << endl; } }; class Test { public: Test() { cout << __func__ << endl; } ~Test() { cout << __func__ << endl; } private: Quest q; }; int main(int argc, const char * argv[]) { shared_ptr<Test> t(new Test); t.reset(); system("pause"); } class Quest { public: Quest() { cout << __func__ << endl; } ~Quest() { cout << __func__ << endl; } }; class Test { public: Test() { cout << __func__ << endl; } ~Test() { cout << __func__ << endl; } private: Quest q; }; int main(int argc, const char * argv[]) { shared_ptr<Test> t(new Test); t.reset(); system("pause"); } class Quest { public: Quest() { cout << __func__ << endl; } ~Quest() { cout << __func__ << endl; } }; class Test { public: Test() { cout << __func__ << endl; } ~Test() { cout << __func__ << endl; } private: Quest q; }; int main(int argc, const char * argv[]) { shared_ptr<Test> t(new Test); t.reset(); system("pause"); } Sorry for the lack of formatting, but here I can do nothing ... - Harry