C++11 constructor argument: std::move and value or std::forward and rvalue reference

家住魔仙堡 提交于 2019-12-03 21:46:24

The two variants differ in functionality. The following statements work for the second one–but not for the first one:

Y y;
X x(y);

If you are looking for the same functionality, the two variants should look as follows:

struct X
{
    Y data_;
    explicit X(const Y& data) : data_(data) { }
    explicit X(Y&& data) : data_(std::move(data)) { }
};

struct X
{
    Y data_;
    explicit X(Y data) : data_(std::move(data)) { }
};

The first variant saves one move operation, whereas the second variant is less to write. So, the answer is: Use the latter as long as you have no reason to optimize the performance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!