简体   繁体   中英

Destructor call AFTER Overloaded Assignment Operator called - C++

I have a Graph pointer called *graph1 and memory has already been allocated for it (note: not part of the question but Graph is a template class). I have also created another instance of Graph called graph2. I called an overloaded assignment operator on them like so

Graph<std::string,std::string> *graph1 = new Graph<std::string,std::string>;
...
... // Called member functions on graph1
Graph<std::string,std::string> graph2;
graph2 = *graph1;

The assignment operator works properly, BUT for some reason Graph's destructor also gets called right after the assignment operator gets called. Is this normal or am I not implementing the assignment operator properly?

This is how I implemented assignment operator:

template <typename VertexType, typename EdgeType>
Graph<VertexType, EdgeType> Graph<VertexType, EdgeType>::operator=(const Graph<VertexType, EdgeType> &source)
{
  std::cout << "\tAssignment Operator called\n\n";
  if(this == &source)
    return *this;

  this->vecOfVertices = source.vecOfVertices;
  this->orderPtr = source.orderPtr;
  this->count = source.count;
  return *this;
}

The correct definition of assignment operator is

Graph<VertexType, EdgeType>& Graph<VertexType, EdgeType>::
    operator=(const Graph<VertexType, EdgeType> &source);

By using Graph<VertexType, EdgeType> as your return type, you are generating an unnecessary creation of a temporary variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM