【发布时间】:2020-02-15 10:28:02
【问题描述】:
对我来说理解指针管理的机制有点复杂。
我尝试通过这种方法减少对班级成员的复制操作:
#include <iostream>
#include <vector>
class Shape {
public:
std::unique_ptr<int> x;
Shape(const Shape& val) = delete; // will be delete by default by compiler?
Shape& operator=(const Shape& val) = delete; // will be delete by default by compiler?
Shape(Shape&& val) noexcept {
this->x = std::move(val.x);
}
Shape& operator=(Shape&& val) noexcept {
std::cout << "Move operator=" << std::endl;
this->x = std::move(val.x);
return *this;
}
Shape() : x(std::unique_ptr<int>(new int)) {
std::cout << "Constructor Shape" << std::endl;
}
Shape(int v) : x(std::unique_ptr<int>(new int(v))) {
std::cout << "Constructor Shape (by value)" << std::endl;
}
virtual ~Shape() {
std::cout << "Destructor Shape" << std::endl;
};
Shape operator+(const Shape& val) {
std::cout << "Move sum" << std::endl;
Shape res(*x + *val.x);
return res;
}
};
int main()
{
Shape a(1);
Shape b(3);
Shape res = a + b;
std::cout << "Value a is (" << *(a.x) << ")" << std::endl;
std::cout << "Value b is (" << *(b.x) << ")" << std::endl;
std::cout << "Value res is (" << *(res.x) << ")" << std::endl;
};
结果是:
构造函数形状(按值) 构造函数形状(按值) 移动总和 构造函数形状(按值) 析构函数形状 值 a 是 (1) 值 b 是 (3) 值 res 是 (4) 析构函数形状 析构函数形状 析构函数形状
将复制构造函数和复制操作符 = 标记为“已删除”是否是个好主意,或者我可以删除这些行? std::move 运算符一个人有多贵?
【问题讨论】:
-
删除拷贝构造函数和拷贝赋值运算符的目的是什么?
-
std::move本身什么都不做——它只是一个演员表,不花任何钱。
标签: c++ copy move operator-keyword