【发布时间】:2014-11-22 07:14:42
【问题描述】:
我不明白为什么以下方法不起作用:
class X{
unsigned int sz;
public:
X(const unsigned int n = 0) : sz(n) {std::cout << "Default constructor called!" << std::endl;};
X(const X& x) : sz(x.sz) {};
X(X&& x) : sz(x.sz) {std::cout << "Move constructor called!" << std::endl;};
};
void foo(X&& x){
std::cout << x.size() << std::endl;
}
int main(){
X x(10);
foo(std::move(x));
foo(X(5));
return 0;
}
这个程序打印:
调用默认构造函数!
调用了默认构造函数!
我知道移动构造函数在这个例子中是没有意义的,因为我们没有窃取任何东西,但是在这些情况下不应该调用移动构造函数吗?
编辑:在 Windows 上使用 g++ 4.8.1。
【问题讨论】:
标签: c++ c++11 move-semantics