gpt4 book ai didi

带有 vector 、指针的 C++ 析构函数,

转载 作者:IT老高 更新时间:2023-10-28 12:43:03 24 4
gpt4 key购买 nike

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

  • std::vectorstd::strings:它们会自动销毁吗?

  • 如果我有类似的东西

    std::vector<myClass*> 

    指向类的指针。调用 vector 析构函数时会发生什么?
    它会自动调用 myClass 的析构函数吗?还是只有 vector 被销毁,但它包含的所有对象仍然存在于内存中?

  • 如果我在一个类中有一个指向另一个类的指针会发生什么,比如:

    class A {
    ClassB* B;
    }

    并且 A 类在代码中的某个位置被销毁。 B 类也会被销毁,还是指针和 B 类仍然存在于内存中的某个地方?

最佳答案

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

是的(假设成员变量不是指向 std::vectorstd::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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com