该值将被复制而不是移动.为什么?

The value gets copied instead of being moved. Why?

本文关键字:移动 为什么 复制      更新时间:2023-10-16

为什么这里声明的对象没有被移动,而是被复制?它与复制省略有某种关系吗?当前代码不应该更改类的对象吗? 最初预计通过使用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。对于非类类型,复制和移动是相同的操作。