析构函数调用AFTER Overloaded Assignment Operator调用 - C++

jbi*_*isa 1 c++ destructor assignment-operator

我有一个名为*graph1的Graph指针,并且已经为它分配了内存(注意:不是问题的一部分,但Graph是模板类).我还创建了另一个名为graph2的Graph实例.我这样调用了一个重载赋值运算符

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;
Run Code Online (Sandbox Code Playgroud)

赋值运算符正常工作,但由于某种原因,在调用赋值运算符后,Graph的析构函数也会被调用.这是正常的还是我没有正确实现赋值运算符?

这是我实现赋值运算符的方式:

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;
}
Run Code Online (Sandbox Code Playgroud)

Lou*_*Lou 6

赋值运算符的正确定义是

Graph<VertexType, EdgeType>& Graph<VertexType, EdgeType>::
    operator=(const Graph<VertexType, EdgeType> &source);
Run Code Online (Sandbox Code Playgroud)

通过使用Graph<VertexType, EdgeType>返回类型,您将生成不必要的临时变量创建.