c++中的赋值运算符模板和复制构造函数
assignment operator template and copy constructor in c++
所以基本上我正在尝试使用赋值运算符来分配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
成为好友函数
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 当从函数参数中的临时值调用复制构造函数时
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 为什么需要复制构造函数,在哪些情况下它们非常有用
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 复制构造函数、赋值运算符C++
- std::ofstream 作为类成员删除复制构造函数?
- 复制构造函数C++无法正确复制指针
- 关于复制构造函数的一个棘手问题
- 为什么调用复制构造函数而不是移动构造函数?
- 填充上编译器生成的复制构造函数之间的不一致
- C++ 对象指针数组的复制构造函数
- C++ 基本 CTOR 说明 - 为什么不调用赋值/复制构造函数
- 防止在复制构造函数中隐式调用基构造函数
- 为用户定义的类正确调用复制构造函数/赋值运算符
- 具有已删除移动和复制构造函数的类的就地构造
- 复制构造函数隐式转换问题
- 复制构造函数中的递归调用