现在的位置: 首页 > 综合 > 正文

PC-LNT error 1732

2013年08月04日 ⁄ 综合 ⁄ 共 995字 ⁄ 字号 评论关闭

 

new in constructor for class 'Name' which has no assignment operator -- Within a
constructor for the cited class, there appeared a new. However, no assignment operator was
declared for this class. Presumably some class member (or members) points to dynamically
allocated memory. Such memory is not treated properly by the default assignment operator.
Normally a custom assignment operator would be needed. Thus, if x and y are both of type
Symbol
x = y;
will result in pointer duplication. A later delete would create chaos. 

这个错误出现的原因就是在一个类的成员变量中,出现动态申请内存的情况(即这个成员变量是指针),但是没有copy constructor和assignment operator存在.这样如果出现两个类进行赋值的时候,有可能造成问题.

这个问题是由Effective C++ Item 11:  Declare a copy constructor and an assignment operator for classes with dynamically allocated memory.来定义的.

最典型的例子就是我们的string类.上次在论坛还见到有人在问面试题,也是考这个的.

解决方法就是增加copy constructor和assignment operator.

如果真的实际情况中赋值的话,那么可以用Effective C++ Item 11中的一个方法:

You declare the functions (private, as it turns out), but you don't define (i.e., implement) them at all.

eg:

class CX

{

private:

// 以下即只声明但是不定义,这样就防止别人使用了

CX(const CX& right);

CX& operator = (const CX& right);

private:

int * m_n;

};

抱歉!评论已关闭.