我有以下简化的代码示例:
#include#include using namespace std; class ShouldBeMovedWhenSwapped { public: // ShouldBeMovedWhenSwapped() = default; // ShouldBeMovedWhenSwapped(ShouldBeMovedWhenSwapped&&) = default; // ShouldBeMovedWhenSwapped(const ShouldBeMovedWhenSwapped&) = default; // ShouldBeMovedWhenSwapped& operator=(ShouldBeMovedWhenSwapped&&) = default; struct MoveTester { MoveTester() {} MoveTester(const MoveTester&) { cout << "tester copied " << endl; } MoveTester(MoveTester&&) { cout << "tester moved " << endl; } MoveTester& operator=(MoveTester) { cout << "tester emplaced" << endl; return *this; } // must be declared if move declared }; MoveTester tester; }; int main() { ShouldBeMovedWhenSwapped a; ShouldBeMovedWhenSwapped b; std::swap(a,b); return 0; }
我正在使用MinGW,在运行'gcc --version'时,我得到了gcc 4.7.2
编辑:对于第一个问题,请参阅问题中的评论.它似乎是gcc中的一个错误.
代码的输出取决于注释掉的构造函数.但我不明白为什么会出现差异.每个输出背后的原因是什么?
// Everything commented out tester moved tester copied <---- why not moved? tester emplaced tester copied <---- why not moved? tester emplaced // Nothing commented out tester moved tester moved tester emplaced tester moved tester emplaced // Move constructor commented out tester copied tester moved tester emplaced tester moved tester emplaced
对于我的第二个问题(这就是为什么我开始这个测试) - 假设我有一个大型向量而不是类MoveTester的真实案例,我怎样才能确定向量移动而不是在这种情况下被复制?