假设我有以下类,它有一个方法 set_value
。哪种实现方式更好?
class S {
public:
// a set_value method
private:
Some_type value;
};
按值传递,然后 move
void S::set_value(Some_type value)
{
this->value = std::move(value);
}
定义两个重载方法
void S::set_value(const Some_type& value)
{
this->value = value;
}
void S::set_value(Some_type&& value)
{
this->value = std::move(value);
}
第一种方法只需要定义一个方法,而第二种方法需要两个。
然而,第一种方法似乎效率较低:
- 根据传递的参数复制/move 参数的构造函数
- move 作业
- 参数的析构函数
而对于第二种方法,只执行一次赋值操作。
- 根据调用的重载方法复制/move 赋值
那么,哪种实现方式更好呢?还是根本不重要?
还有一个问题:下面的代码是否等同于第二种方法中的两个重载方法?
template <class T>
void S::set_value(T&& value)
{
this->value = std::forward<T>(value);
}
编译器可以自由地删除(优化掉)拷贝,即使这样做会产生副作用。因此,按值传递并 move 结果实际上为您提供了两种方法解决方案的所有性能优势,同时只为您提供了一个代码路径来维护。您绝对应该更喜欢按值传递。
举个例子来证明:
#include <iostream>
struct XYZ {
XYZ() { std::cout << "constructed" << std::endl; }
XYZ(const XYZ&) {
std::cout << "copy constructed" << std::endl;
}
XYZ(XYZ&&) noexcept {
try {
std::cout << "move constructed" << std::endl;
}
catch(...) {
}
}
XYZ& operator=(const XYZ&) {
std::cout << "assigned" << std::endl;
return *this;
}
XYZ& operator=(XYZ&&) {
std::cout << "move-assigned" << std::endl;
return *this;
}
};
struct holder {
holder(XYZ xyz) : _xyz(std::move(xyz)) {}
void set_value(XYZ xyz) { _xyz = std::move(xyz); }
void set_value_by_const_ref(const XYZ& xyz) { _xyz = xyz; }
XYZ _xyz;
};
using namespace std;
auto main() -> int
{
cout << "** create named source for later use **" << endl;
XYZ xyz2{};
cout << "\n**initial construction**" << std::endl;
holder h { XYZ() };
cout << "\n**set_value()**" << endl;
h.set_value(XYZ());
cout << "\n**set_value_by_const_ref() with nameless temporary**" << endl;
h.set_value_by_const_ref(XYZ());
cout << "\n**set_value() with named source**" << endl;
h.set_value(xyz2);
cout << "\n**set_value_by_const_ref() with named source**" << endl;
h.set_value_by_const_ref(xyz2);
return 0;
}
预期输出:
** create named source for later use **
constructed
**initial construction**
constructed
move constructed
**set_value()**
constructed
move-assigned
**set_value_by_const_ref() with nameless temporary**
constructed
assigned
**set_value() with named source**
copy constructed
move-assigned
**set_value_by_const_ref() with named source**
assigned
请注意复制/move 版本中没有任何冗余拷贝,但在使用无名临时调用 set_value_by_const_ref()
时会出现冗余复制分配。我注意到最终案例的明显效率提升。我认为 (a) 这在现实中是一个极端情况,并且 (b) 优化器可以处理它。
我的命令行:
c++ -o move -std=c++1y -stdlib=libc++ -O3 move.cpp