Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
重载赋值运算符调用后的析构函数调用-C++_C++_Destructor_Assignment Operator - Fatal编程技术网

重载赋值运算符调用后的析构函数调用-C++

重载赋值运算符调用后的析构函数调用-C++,c++,destructor,assignment-operator,C++,Destructor,Assignment Operator,我有一个名为*graph1的图形指针,并且已经为它分配了内存注意:这不是问题的一部分,但Graph是一个模板类。我还创建了另一个名为graph2的Graph实例。我这样对它们调用了重载赋值运算符 Graph<std::string,std::string> *graph1 = new Graph<std::string,std::string>; ... ... // Called member functions on graph1 Graph<std::stri

我有一个名为*graph1的图形指针,并且已经为它分配了内存注意:这不是问题的一部分,但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;
赋值运算符工作正常,但由于某种原因,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;
}

赋值运算符的正确定义是

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

通过使用图形作为返回类型,您正在生成不必要的临时变量创建。

赋值运算符的正确定义是

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

通过使用Graph作为返回类型,您正在生成一个不必要的临时变量创建。

您知道析构函数在哪个对象上运行吗?您知道析构函数在哪个对象上运行吗?哇。我自己也应该看到这一点,对到处都要编写模板参数感到困惑。谢谢你的帮助!哇!我自己也应该看到这一点,对到处都要编写模板参数感到困惑。谢谢你的帮助!