Object copy constructor deepens

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;
...	 

}

In the main function, both sides are output continuously, and the output of the second pass is garbled and error.
Bewildered, check the data and find that this may be the pot of the copy constructor.
When the object is passed in as a formal parameter, the function will temporarily copy an object that is the same as the actual parameter. Since no copy constructor is defined, the default copy constructor can only be used. At the end of the function, the local variable is destructed. The formal parameters are simply copied, so they are also destructed, which will cause the risk of repeated destructuring

Avoid method

Can use references as much as possible, so that there is no need to temporarily create a local variable, which saves time and saves time.
It can also be solved by overwriting the copy constructor

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

Published 20 original articles · praised 3 · visits 462

Guess you like

Origin blog.csdn.net/qq_44893580/article/details/103641516