[英]Destructor call AFTER Overloaded Assignment Operator called - C++
我有一個名為* 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;
賦值運算符正常工作,但由於某種原因,在賦值運算符被調用后,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>
作為返回類型,可以生成不必要的臨時變量創建。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.