C++ Destructors with Vectors, Pointers,

2019-02-11 16:02发布

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 about other objects in C++:

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

  • If I have something like

    std::vector<myClass*> 
    

    of pointers to classes. 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?

  • What happens if I have a pointer to another class inside a class, say:

    class A {
      ClassB* B;
    }
    

    and Class A is destroyed at some point in the code. Will Class B be destroyed too or just the pointer and class B will be still existent somewhere in the memory?

8条回答
走好不送
2楼-- · 2019-02-11 16:50

If I have something like std::vector what happens when the vector destructor is called?

It depends.

If you have a vector of values std::vector <MyClass>, then the destructor of the vector calls the destructor for every instance of MyClass in the vector.

If you have a vector of pointers std::vector <MyClass*>, then you're responsible for deleting the instances of MyClass.

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

ClassB instance would remain in memory. Possible ways to have ClassA destructor to make the job for you are to make B an instance member or a smart pointer.

查看更多
叼着烟拽天下
3楼-- · 2019-02-11 16:52

You only need to worry about for the memory you have created dynamically (When you reserve memory with new.)

For example:

Class Myclass{
   private:
       char* ptr;
   public:
       ~Myclass() {delete[] ptr;};
}
查看更多
登录 后发表回答