加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 哪种重载组合效果最好?

发布时间:2020-12-16 09:55:40 所属栏目:百科 来源:网络整理
导读:我有这样的功能: void init_str(std::string _s){ std::string s{_s};} 我希望通过允许const char *重载来避免创建临时std :: string来进行优化. void init_str(const char* c){ std::string s{c};} 但我也可以使用转发. templatetypename Tvoid init_str(T
我有这样的功能:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读