首页 > 解决方案 > 深拷贝指针和删除内存

问题描述

我正在尝试创建复制构造函数。

例如,有一个像这样的类:

#include <string>
#include <vector>
using namespace std;
class Test
{
    vector<string*> name;
public:
    ~Test();
    Test(const string& name);
    Test(const Test& t);
};

Test::Test(const Test& t)
{
    for (auto it = t.name.begin(); it != t.name.end(); it++) {
        this->name.push_back((*it));
    }
}

Test::Test(const string& name)
{
    this->name.emplace_back(name);
}

Test::~Test() {
    for (auto it = name.begin(); it != name.end(); it++) {
        delete (*it);
        (*it) = nullptr;
    }
}

int main() {
    Test t("Hello World!");
    Test t2(t);
}

程序完成后,出现错误: Access violation reading location 0xDDDDDDDD

我知道,这是因为在调用 t2 时 t 的名称已被删除,但是我不知道如何深度复制名称向量。

谢谢您的帮助。

标签: c++

解决方案


为了进行深度复制,您需要复制任何指针指向的内容。
像这样:

name.push_back(new string(**it));

您还需要实现复制赋值运算符。


推荐阅读