c++中的赋值运算符模板和复制构造函数

assignment operator template and copy constructor in c++

本文关键字:复制 构造函数 赋值运算符 c++      更新时间:2023-10-16

所以基本上我正在尝试使用赋值运算符来分配2个变量:

S solutionCourante, bestSolution; //(S is a template class)
bestSolution = solutionCourante = solutionInitiale;

这是我要处理的操作员:

template <class S, class T>
const Graphe<S,T> & Graphe<S,T>::operator = (const Graphe<S,T> & graphe)
{
this->lSommets = graphe.lSommets->copieListe(graphe.lSommets);
this->lAretes = graphe.lAretes->copieListe(graphe.lAretes);
return *this;
}

这是我的复制构造函数:

template <class S, class T>
Graphe<S,T>::Graphe(const Graphe<S,T> & graphe)
{
 *this = graphe;
}

(我知道构造函数副本编码有点糟糕,但有效)

所以在任何时候,我都可以看到"bestSolution"answers"solutionCourante"不是NULL,而是空的,我不明白为什么,因为在我的运算符中"monGrape"被填充了。所以当我第一次尝试做这个运算符时,返回值时似乎做错了什么。

根据:

const Graphe<S,T> & Graphe<S,T>::operator = (const Graphe<S,T> & graphe)

graphe是我想复制的项目,我们得到了*this=graphe?

赋值运算符应该为"this"赋值,而不是分配新值。

template <class S, class T>
Graphe<S,T> & Graphe<S,T>::operator = (const Graphe<S,T> & graphe)
{
    lSommets = graphe.lSommets ? new PElement<Sommet<T>>(*graphe.lSommets) : nullptr;
    lAretes = graphe.lAretes ? new PElement<Arete<S,T>>(*graphe.lAretes) : nullptr;
    prochaineClef = graphe.prochaineClef;
    return *this;
}
template <class S, class T>
Graphe<S,T>::Graphe(const Graphe<S,T> & graphe)
{
    *this = graphe;
}

一般来说,您不应该用new返回堆上分配的东西,因为任何所有权信息都会丢失。您可能应该尝试使用智能指针,例如std::unique_ptr。

已经发布了一个答案,但使用了一种让赋值运算符完成大部分工作的方法。

既然您已经对复制构造函数进行了编码,那么您的赋值运算符应该使用复制/交换习惯用法来编写:什么是复制和交换习惯用法?

通常所做的(如果你想在赋值运算符和复制构造函数之间发挥协同作用)是让复制构造函数完成大部分工作,而赋值运算符使用复制构造函数(和析构函数)。

这是您使用复制/交换的代码:

#include <algorithm>
//...
template <class S, class T>
class Graphe 
{
    //...
    friend void swap(Graphe<S,T>& lhs, Graphe<S,T>& rhs)
    {
        std::swap(lhs.lAretes, rhs.lAretes);
        std::swap(lhs.lSommets, rhs.lSommets);
        std::swap(lhs.prochaineClef, rhs.prochaineClef);
    }
  //...
};
//...
template <class S, class T>
Graphe<S,T>::Graphe(const Graphe<S,T> & graphe) : 
{
    lSommets = graphe.lSommets ? new PElement<Sommet<T>>(*graphe.lSommets) : nullptr;
    lAretes = graphe.lAretes ? new PElement<Arete<S,T>>(*graphe.lAretes) : nullptr;
    prochaineClef = graphe.prochaineClef;
}
template <class S, class T>
Graphe<S,T>& Graphe<S,T>::operator = (Graphe<S,T> graphe)
{
    swap(*this, graphe);
    return *this;
}

向模板类中添加了一个名为swap的函数,该函数仅在左手参数和右手参数之间交换所有成员。如果你没有发布所有班级成员,我会强调all

假设您的复制构造函数没有错误,并且析构函数正在工作并且没有错误,那么上面的代码将正常工作。

编辑:根据T.C.的评论,使swap成为好友函数