我有这样一个函数:
void init_str(std::string _s)
{
std::string s{_s};
}
我想通过允许 const char*
重载来进行优化,以避免创建临时 std::string
。
void init_str(const char* c)
{
std::string s{c};
}
但我也可以使用转发。
template<typename T>
void init_str(T&& t)
{
std::string s{std::forward<T>(t)};
}
但是编译器对重载的偏好是:
const char*
- 转发
std::string
那么我应该更喜欢哪种重载组合?
最佳答案
假设使用 c++11 或更高版本,性能最高的解决方案是您尚未尝试过的解决方案:
void init_str(std::string s)
{
// just use s
}
因为复制省略将确保根本不会构造不必要的临时对象。
使用 std::string(const char*) 构造函数构造 s(总共 1 个构造函数):
init_str("xxx");
这个用拷贝构造函数构造了s:
std::string x; // 1 constructor
init_str(x); // 1 copy constructor
这用移动构造函数构造了 s
std::string x; // 1 constuctor
init_str(std::move(x)); // 1 move constructor
这实际上根本没有创建临时文件:
std::string get_str() {
std::string s("xxx"); // 1 constructor, but...
return s; // ...because of RVO it's constructed at the call site
}
init_str(get_str()); // ... which is actually the constructor of s in init_str's arg list
// ... total constructors: 1
关于c++ - 哪种重载组合性能最高?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27580342/