在赋值移动运算符内部使用交换
Using swap inside assignment move operator
I c++编程语言13.6.2 std::swap用于实现移动语义,其思想如下:
class greenCars{
public:
greenCars(){std::cout<<"DSn";}
greenCars& operator=(const greenCars& other){
greenCars tmp;
swap(*this, tmp);
return *this;
}
greenCars(deutscheSchweine&& other){}
greenCars& operator=(greenCars&& other){
swap(*this, other);
return *this;
}
};
int main(){
greenCars ds;
greenCars ds2;
ds2 = ds;
我上面的例子在调用赋值之后,我们可以使用move语义来狂热地从临时复制,但这个例子导致递归调用move赋值。我的问题是,我们是否可以使用移动语义中的交换,但以某种适当的方式?
通过交换实现拷贝分配是个好主意,但您错过了一些细节。
您需要在某个时刻对每个成员调用move。这可以通过调用swap(*this, other);
并实现swap
的专门化来实现,也可以通过在每个成员上直接调用swap
来实现,或者通过让std::swap
调用移动分配运算符来实现。
不应使用swap
执行移动分配。
我们已经有了一个优秀的指南";复制和交换";成语,这里:什么是复制和交换成语?
另请阅读C++11中的复制和交换习语应该变成复制和移动习语吗?
最后,您想要的(假设您的成员对象设计正确)是:
class greenCars
{
public:
greenCars(){std::cout<<"DSn";}
// defaulted move operations (member-wise moves)
greenCars(greenCars&& other) = default;
greenCars& operator=(greenCars&& other) = default;
// copy construction is defaulted (member-wise copies)
greenCars(const greenCars& other) = default;
// copy assignment uses copy-and-move for exception safety
greenCars& operator=(greenCars other)
{
return *this = std::move(other);
}
};
相关文章:
- 将函数类成员映射到类本身内部
- Boost Spirit,获取迭代器内部语义动作
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 内联函数中具有内部链接的全局变量
- 在函数内部的声明中初始化数组,并在外部使用它
- 如何在不知道向量大小的情况下输入向量内部的向量?
- C++嵌套if语句,基本货币交换
- 卷曲bracers内部结构的声明
- shell排序中的交换和比较
- 从函数角度看ID到文件路径的内部与外部映射
- spdlog标头仅与外部fmt一起使用.spdlog错误:'内部':不是'fmt'
- 如何在pugixml中获取节点的内部XML
- 使用C链接在函数内部创建C++模板
- 指针没有更新它在void函数内部指向的值
- 方法内部但循环仍得到预期的不合格id错误C++
- 对象内部有大量数据容器,实现更高效的对象交换
- 在赋值移动运算符内部使用交换
- 与SIMD内部函数进行比较和交换
- 复制和交换技术在赋值操作符函数内部使用复制构造函数
- 您如何在不暴露内部信息的情况下与 Pimpl 交换私人数据