指针 - 重复的对象实例

时间:2012-12-27 05:57:05

标签: c++ pointers

如果我有

Class *a1 = new Class();
Class *b1 = a1;

delete b1;
delete a1; //this will give a double free or corruption message;

如果我删除指针b,它与删除指针一样正确吗?由于两者都指向同一个Class实例。那么,如何将a1的实例复制到b1,以便在删除b1时,不删除a1。

Class *a1 = new Class();
Class *b1 = a1;

//how do I duplicate the instance a1 is pointing
//so that when I delete b1, a1 still exists.

delete b1; 
delete a1; //this is still valid 

感谢。

1 个答案:

答案 0 :(得分:12)

你有使用指针和分配的原因吗?还有它的简单

Class a1;
...
Class b1 = a1;

此处无需删除。

如果你需要按原样保留结构

Class *a1 = new Class();
Class *b1 = new Class(*a1);

Class *a1 = new Class();
Class *b1 = new Class();
*b1 = *a1;

这假设你有一个有效的拷贝构造函数(例如#1)或赋值运算符(例如#2)

p.s:尝试使用std::unique_ptr而不是原始指针来更安全。