Re: [cpp] 初次光临,请多指教

Stone Jiang 2005119 at gmail.com
Mon Jul 10 16:21:42 CST 2006


应该是这个类没有正确拷贝构造函数和赋值函数.
这时系统分生成一个按位拷贝的缺省版本.


xWrapper   w1;
xWrapper  w2;
w2 = w1;
这时,w1和w2这两个对象的xItem指向位置同时是w2.xItem的地址,原来w1.xItem已经永远不会被系统收回.

在析构中,两个对象要析构两次w2.xItem
所以系统要崩溃.

解决的办法是,实现完整的Big Four函数.或者,禁止用户调用拷贝构造函数和赋值函数/
具体做法是把拷贝构造函数和赋值函数放在私有部分.


On 7/10/06, ling <xl-yc-lzj at necsoft.com.cn> wrote:
>
> 今天看了c++对话系列,为什么说下面的类程序会因为内存问题而崩溃呢?
>
> #include "xStruct.h" // definition of struct X
>
> class xWrapper
> {
>     X* xItem;
> public:
>     xWrapper() : xItem(new X) { }
>     ~xWrapper() { delete xItem; }
>
>     void dump() { /* dumps xItem to cout */ }
> };
>
> _______________________________________________
> Cpp mailing list
> Cpp at codingnow.com
> http://codingnow.com/mailman/listinfo/cpp
>
>


-- 
Take care
Stone Jiang
blog:  http://blog.csdn.net/FocusOnACE/



More information about the Cpp mailing list