指针 - 重复对象实例 [英] pointers - duplicate object instance

查看:139
本文介绍了指针 - 重复对象实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有

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

delete b1;
delete a1; //这将给出一个双重免费或腐败的消息;

如果我删除指针b,它和删除指针一样吗?因为两者都指向同一个Class的实例。因此,我如何将a1的实例复制到b1,这样当我删除b1时,a1不会被删除。

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

//如何复制实例a1指向
//,这样当我删除b1时,a1仍然存在。

delete b1;
delete a1; //这仍然有效

谢谢。

解决方案

有没有理由使用指针和分配?其它简单的

 类a1; 
...
类b1 = a1;

这里不需要删除。



如果你需要保持结构,因为你需要做

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

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

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



ps:尝试使用 std :: unique_ptr ,而不是原始指针,

If I have

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

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

if I delete pointer b, it's the same as deleting pointer a right? Since the two are pointing at the same instance of Class. So, how can I copy the instance of a1 to b1 so that when I delete b1, a1 is NOT deleted.

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 

Thanks.

解决方案

Is there a reason you are using pointers and allocation? Else its as simple as

Class a1;
...
Class b1 = a1;

There is no need here for a delete.

If you need to keep the structure as it is you need to do

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

or

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

This assumes you have a valid copy-constructor ( e.g #1) or assignment operator (e.g #2)

p.s: try to use std::unique_ptr instead of raw pointers to be safer.

这篇关于指针 - 重复对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆