C++ Destructors with Vectors, Pointers,

后端 未结 7 2049
清酒与你
清酒与你 2020-12-15 02:57

As far as I know, I should destroy in destructors everything I created with new and close opened filestreams and other streams. However, I have some doubts abou

7条回答
  •  孤街浪徒
    2020-12-15 03:32

    std::vector and std::strings: Are they destroyed automatically?

    Yes (assuming member variables are not pointers to std::vector and std::string).

    If I have something like std::vector what happens when the vector destructor is called? Would it call automatically the destructor of myClass? Or only the vector is destroyed but all the Objects it contains are still existant in the memory?

    If vector then all objects contained in the vector will be destroyed. If vector then all objects must be explicitly deleted (assuming the class being destructed owns the objects in the vector). A third alternative is vector of smart pointers, like vector>, in which case the elements of the vector do not need to be explictly deleted.

    What happens if I have a pointer to another class inside a class

    The B must be explicitly deleted. Again, a smart pointer could be used to handle the destruction of B.

提交回复
热议问题