我正在尝试创建复制构造函数。
例如,有这样一个类:
class Test
{
vector<string*> name;
public:
~Test();
Test(const string& name);
Test(const Test& t);
};
Test::Test(const Test& t)
{
for (auto it = t.ticket.begin(); it != t.ticket.end(); it++) {
this->name.push_back((*it));
}
}
Test::~Test(){
for (auto it = name.begin(); it != name.end(); it++) {
delete (*it);
(*it) = nullptr;
}
}
int main() {
Test t("Hello World!");
Test t2(t);
}
当程序完成时,出现错误:访问违规读取位置0xDDDDDDD
我知道,这是因为当t2被调用时t的名字已经被删除了,但是我不知道如何深度复制名字向量。
谢谢你的帮助。
为了进行深度复制,您需要复制任何指针所指向的内容。
如下所示:
name.push_back(new string(**it));
您还需要实现复制赋值运算符。