move对象之后,新旧对象之间有依赖关系吗?int main () {
int a = 100;
std::cout<<&a<<std::endl;
auto a_copy = a; // deduced as int
std::cout<<&a_copy<<std::endl;
auto a_move = std::move(a); // deduced as int
std::cout<<&a_move<<std::endl;
};输出:
0x7fffffffe094
0x7fffffffe098
0x7fffffffe09c发布于 2015-01-11 23:48:59
在这个例子中,没有区别。我们最终将得到3个值为100的int。不过,不同的类型肯定会有所不同。例如,让我们考虑像vector<int>这样的东西
std::vector<int> a = {1, 2, 3, 4, 5}; // a has size 5
auto a_copy = a; // copy a. now we have two vectors of size 5
auto a_move = std::move(a); // *move* a into a_move最后一个变量a_move获得了a内部指针的所有权。所以我们最终得到的是a_move是一个大小为5的向量,但a现在是空的。move比copy效率高得多(想象一下,如果它是一个1000个字符串的向量- a_copy需要分配1000个字符串的缓冲区和复制1000个字符串,但a_move只分配了几个指针)。
对于其他一些类型,其中一个可能是无效的:
std::unique_ptr<int> a{new int 42};
auto a_copy = a; // error
auto a_move = std::move(a); // OK, now a_move owns 42, but a points to nothing但对于许多类型,没有区别:
std::array<int, 100> a;
auto a_copy = a; // copy 100 ints
auto a_move = std::move(a); // also copy 100 ints, no special move ctor更一般地说:
T a;
auto a_copy = a; // calls T(const T& ), the copy constructor
auto a_move = std::move(a); // calls T(T&& ), the move constructor发布于 2015-01-11 23:50:44
使用std::move只是将左值更改为x值,因此它有资格与移动构造函数和移动赋值操作符一起使用。这些对于内置类型是不存在的,所以在本例中使用move没有区别。
发布于 2015-01-11 23:44:06
在这个例子中,默认拷贝和std::move有什么区别?
这是没有区别的。复制满足move的要求,在内置类型的情况下,move实现为copy。
移动对象后,新旧之间是否存在依赖关系
不,没有依赖项。这两个变量是独立的。
https://stackoverflow.com/questions/27888873
复制相似问题