具有向量,指针的C ++析构函数 [英] C++ Destructors with Vectors, Pointers,

查看:78
本文介绍了具有向量,指针的C ++析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,我应该在析构函数中销毁使用 new 创建的所有内容,并关闭打开的文件流和其他流。
但是,我对C ++中的其他对象有一些疑问:

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 ::向量 std :: string s:它们会自动销毁吗?

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

如果我有类似的东西

std::vector<myClass*> 

指向类的指针。

会自动调用 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;
}

并且在代码中的某个点销毁了A类。 B类也会被破坏还是仅指针和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?

推荐答案


std :: vector和std :: strings:它们会自动销毁吗?

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

是(假设成员变量不是指向 std ::的指针):向量 std :: string )。

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


如果我有类似std :: vector之类的东西,当调用向量析构函数时会发生什么?
会自动调用myClass的析构函数吗?还是仅销毁了矢量,但其中包含的所有对象在内存中仍然存在?

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?

如果 vector < ; MyClass> ,则向量中包含的所有对象都将被销毁。如果 vector< MyClass *> ,那么所有对象都必须显式地 delete d(假设被销毁的类拥有这些对象)在 vector 中)。第三种选择是智能指针的 vector ,例如 vector< shared_ptr< MyClass>> ,在这种情况下,元素向量的内容不需要显式删除 d。

If vector<MyClass> then all objects contained in the vector will be destroyed. If vector<MyClass*> 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<shared_ptr<MyClass>>, 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

B 必须明确地 delete d。同样,可以使用智能指针来处理 B 的破坏。

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

这篇关于具有向量,指针的C ++析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆