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

社会主义新天地 提交于 2019-12-05 04:00:39

问题


Which of the below two should be preferred and why?

struct X {
    Y data_;
    explicit X(Y&& data): data_(std::forward<Y>(data)) {}
};

vs

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

回答1:


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.



来源:https://stackoverflow.com/questions/22332333/c11-constructor-argument-stdmove-and-value-or-stdforward-and-rvalue-refer

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