本文介绍了C ++ 11构造函数参数:std :: move和value或std :: forward和rvalue引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面哪两个应该是首选,为什么?
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)) {}
};
推荐答案
以下语句适用于第二个语句,但不适用于第一个语句:
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.
这篇关于C ++ 11构造函数参数:std :: move和value或std :: forward和rvalue引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!