为什么这里声明的对象没有被移动,而是被复制了?它与拷贝省略有什么关系吗?目前的代码不应该改变班级'对象? 最初预计通过使用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;
}
答案 0 :(得分:4)
您在std::move
上呼叫int
。对于非类类型,复制和移动是相同的操作。