请参阅第10.4.4.1节“复制对象”的TC ++ PL第3版 [英] refer to section 10.4.4.1 "copying object" of TC++PL 3rd edition

查看:136
本文介绍了请参阅第10.4.4.1节“复制对象”的TC ++ PL第3版的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类表{
name * p; int i;

public:

table(int j = 15){p = new name [i = j]} //构造函数

〜table ){delete [] p;}
}

 void h()     
{
    table t1;  
    table t2=t1; 
    table t3;  
    t3=t2;
}`

Bjarne为 t1 t1 中出现的 t1 t2 t3 **

Bjarne wrote array created for t1 will be deleted 3 times as array created for t1 appears in t1,t2,t3**

你能解释一下其他示例。

Can you please explain what does this mean with some other examples.

推荐答案

如果复制构造函数和operator =只复制指针的值, t3将具有指向存储器的相同位的指针。如果表有一个删除指针的析构函数,同一个指针将被删除三次 - 每个对象一次。这将导致一个segfault。

If the copy constructor and operator = only copy the value of a pointer, in the end t1, t2 and t3 will have pointers to the same bit of memory. If table has a destructor that deletes the pointer, the same pointer will be deleted three times - once for every object. This should cause a segfault.

为了防止这个类可以为每个副本分配一个新的数组(称为深度复制),或执行参考计数

To prevent this a class can allocate a new array for every copy (called making a deep copy), or do reference counting.

这篇关于请参阅第10.4.4.1节“复制对象”的TC ++ PL第3版的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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