对象复制构造函数加深

template<class T>
void chainList<T>::output(ostream& out) const
{// Put the list into the stream out.
 for (chain<T>* currentNode = firstNode;
  currentNode != NULL;
  currentNode = currentNode->next)
  out << currentNode->element << "  ";
}
template<class T>
ostream& operator<<(ostream& out, chainList<T>x) 
{                 
 x.output(out);
 return out;
}
...
int main()
{
...
	 cout << my << endl;
	 cout << my << endl;
...	 

}

在主函数里连续输出两边,第二遍输出为乱码且出错。
百思不得其解,查阅资料发现这可能是复制构造函数的锅。
当对象作为形参传入时,函数会临时复制一个和实参一样的对象,由于没有定义复制构造函数,只能采用默认的复制构造函数,在函数结束的时候,局部变量被析构,由于形参只是简单的复制,所以也被析构了,这就会发生重复析构的危险

避免方法

能用引用尽量用引用,这样就不用再临时创建一个局部变量,又节省了时间,又剩了事
也可以通过补写复制构造函数来解决

template<class T>
chainList<T>::chainList(const chainList<T>&theList)
{
   size=theList.size;}

发布了20 篇原创文章 · 获赞 3 · 访问量 462

猜你喜欢

转载自blog.csdn.net/qq_44893580/article/details/103641516