【问题标题】:Move constructor not working?移动构造函数不起作用?
【发布时间】: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


    【解决方案1】:

    为什么?您只是将右值引用传递给您的函数,而不是创建新对象。

    X x(10); // default constructor
    foo(std::move(x)); // passing x as an rvalue
    foo(X(5)); // creating an object (with the default constructor) which is passed as an rvalue
    

    试试X y(std::move(x)),应该会调用你的移动构造函数。

    只有在使用右值引用创建新对象时才会调用移动构造函数。

    【讨论】:

    • "只有在使用右值引用创建新对象时才会调用移动构造函数。" - 这就解释了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-05-22
    • 2015-02-21
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多