c++ - 深拷贝指针和删除内存
问题描述
我正在尝试创建复制构造函数。
例如,有一个像这样的类:
#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 的名称已被删除,但是我不知道如何深度复制名称向量。
谢谢您的帮助。
解决方案
为了进行深度复制,您需要复制任何指针指向的内容。
像这样:
name.push_back(new string(**it));
您还需要实现复制赋值运算符。
推荐阅读
- codenameone - 代号一 - 以编程方式在搜索栏中开始编辑
- c# - 如何通过在 VS 2017 中按日期访问 TFS Warehouse 来获取任务 ID、功能 ID、完成小时数?
- ruby - 合并哈希数组中的重复值
- ruby - 如何查找 Google sheet API v4 的令牌
- postgresql - 可以为具有更多死元组的表的实时数据库运行真空完整详细命令吗?
- javascript - 根据 Knockout.js 中选择列表的选定选项显示或隐藏 HTML 元素?
- selenium - 直到在 Selenium 3 中被弃用
- python - 列表中字符串中间的正则表达式(Python)
- c# - 抛出异常的性能注意事项(重构此模式的最佳方法)
- php - 如何处理具有多种角色类型的同一用户