该值将被复制而不是移动.为什么?
The value gets copied instead of being moved. Why?
为什么这里声明的对象没有被移动,而是被复制?它与复制省略有某种关系吗?当前代码不应该更改类的对象吗? 最初预计通过使用std::move,B的内部结构会改变。我忽略了什么吗?有什么解决方法吗?
#include <iostream>
#include <algorithm>
#include <vector>
class A {
public:
A() {}
auto&& get() { return v; }
friend std::ostream& operator<<(std::ostream& o, A const& a) {
o << "A: ";
for (auto it = std::begin(a.v); it != std::end(a.v); ++it) { if (it != std::begin(a.v)) { o << " "; } o << *it; }
return o;
}
private:
std::vector<int> v;
};
class B {
public:
B() {};
auto&& get() { return v; }
friend std::ostream& operator<<(std::ostream& o, B const& b) {
o << "B: { ";
for (auto it = std::begin(b.v); it != std::end(b.v); ++it) { if (it != std::begin(b.v)) { o << " } { "; } o << *it; }
return o << " }";
}
private:
std::vector<A> v;
};
int main() {
A a, a1, a2; B b;
a.get().insert(a.get().end(), {1, 2, 3, 4});
a1.get().insert(a1.get().end(), {5, 6, 7, 8});
a2.get().insert(a2.get().end(), {9, 10, 11, 12});
std::cout << a << "n" << a1 << "n" << a2;
b.get().insert(b.get().end(), {a, a1, a2});
std::cout << "n" << b << "n";
a.get().push_back(std::move(b.get()[2].get()[2]));
std::cout << a << "n" << a1 << "n" << a2;
std::cout << "n" << b;
return 0;
}
你在int
上调用std::move
。对于非类类型,复制和移动是相同的操作。
相关文章:
- 为什么复制而不是移动数据元素?
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- 为什么调用复制构造函数而不是移动构造函数?
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 为什么 std::memmove 中联合的默认非平凡移动构造函数C++?
- 为什么协程的返回类型必须是可移动构造的?
- C++:为什么不调用移动构造函数?
- 为什么 std::vector 需要 is_trivial 才能按位移动,而不仅仅是is_trivially_copya
- C ++为什么在移动构造函数中需要移动/前进
- 为什么参数在构造 std::thread 时移动两次
- 为什么在删除"移动构造函数"时使用"复制构造函数"?
- std::async 如何工作:为什么它会调用这么多次复制/移动?
- 为什么这里不调用移动构造函数?
- 为什么不调用移动构造函数
- 为什么 std::move 不将默认移动构造函数中的源变量更改为默认值?
- 为什么调用移动分配?
- 为什么移动 std::可选不重置状态
- 为什么我的蛇只向上移动
- 该值将被复制而不是移动.为什么?
- c++数组比较和移动?为什么苹果不动?