- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
据我所知,我应该在析构函数中销毁我用 new
创建的所有内容,并关闭打开的文件流和其他流。但是,我对 C++ 中的其他对象有些怀疑:
std::vector
和std::string
s:它们会自动销毁吗?
如果我有类似的东西
std::vector<myClass*>
指向类的指针。调用 vector 析构函数时会发生什么?
它会自动调用 myClass
的析构函数吗?还是只有 vector 被销毁,但它包含的所有对象仍然存在于内存中?
如果我在一个类中有一个指向另一个类的指针会发生什么,比如:
class A {
ClassB* B;
}
并且 A 类在代码中的某个位置被销毁。 B 类也会被销毁,还是指针和 B 类仍然存在于内存中的某个地方?
最佳答案
std::vector and std::strings: Are they destroyed automatically?
是的(假设成员变量不是指向 std::vector
和 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?
如果 vector<MyClass>
那么 vector 中包含的所有对象都将被销毁。如果 vector<MyClass*>
那么所有对象都必须显式 delete
d(假设被破坏的类拥有 vector
中的对象)。第三种选择是vector
智能指针,如 vector<shared_ptr<MyClass>>
, 在这种情况下 vector
的元素不需要明确delete
d.
What happens if I have a pointer to another class inside a class
B
必须明确 delete
d。同样,可以使用智能指针来处理 B
的销毁。 .
关于带有 vector 、指针的 C++ 析构函数,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12068950/
我是一名优秀的程序员,十分优秀!