首页 > c++移动构造函数什么时候会被调用?

c++移动构造函数什么时候会被调用?

class x{
public:
    x( moveClass&& item) {
        std::cout << 123 << std::endl;
    }
    
    x() = default;
};


int main(){
    x(x());
}

如上的代码, 不应该输出123吗, 为什么什么都没有输出... 这种情况到底算调用了哪种构造方法.


试试x{x{}}


你的代码不应该输出123吧。那是个函数声明,并没有调用x(moveClass&& item)。我的理解是移动构造函数是用在右值身上,减少临时构造函数和析构函数的调用的,当你用右值来调用构造函数的时候,移动构造函数就可以拿来调用。

#include <iostream>

using namespace std;

class x
{
public:
    x(int&& val)
    {
        cout << 123 << endl;
    }
    x() = default;
};

int main()
{
    x(567);

    return 0;
}

上面的代码,因为我传的是个右值进去,所以就会调用构造函数。http://stackoverflow.com/ques...这里面讨论了什么时候用移动构造函数。
题主!!!重大发现,我查资料,然后自己做试验,发现x(x())是一个函数声明!你在你的x(x())下面再声明一个x a,编译运行应该会报错;下面这份是我的测试代码,你也可以试试看,所以你的那一行没有调用移动构造函数!

#include <iostream>
#include <utility>

using namespace std;

class x
{
public:
    x(int&& val)
    {
        cout << "sdfs";
    }
    x()=default;
};

int func()
{
    return 123;
}
class AA
{
public:
    AA(int&&){cout << "no" << endl;}
};

//x(func())
//{
//    cout << "function called" << endl;
//}
//AA(func());
AA(funcall())
{
    cout << "here\n";
}

//x(x());
//AA(x());

int main()
{
    
    //(x)func();
    x(123);
    x(func());
    //AA(123);
    //funcall();
    return 0;
}

#include <iostream>
#include <utility>

class X {
public:
    X( X&& item) {
        std::cout << 123 << std::endl;
    }

    X() = default;
};


int main() {
    X(X()); // X(std::move(X())); 这个会输出 123
}

copy assignment operator 应该这么写:

class X {
    X operator=( const X &rhs ) {
        // ...
    }
}
【热门文章】
【热门文章】