gpt4 book ai didi

c++ - 为什么 emplace_back ("Hello") 调用 strlen?

转载 作者:可可西里 更新时间:2023-11-01 17:44:10 27 4
gpt4 key购买 nike

Justin's answer在另一个问题上做了一个我觉得很有趣但无法解释的观察。考虑以下代码:

std::vector<std::string> v;
v.push_back("Hello, world!"); // Doesn't call strlen.
v.emplace_back("Hello, world!"); // Calls strlen.

如果您查看程序集, emplace_back generates a call to strlen , 而 push_back does not (使用 -Ofast 在 gcc 8.1 和 clang 6.0 中测试)。

为什么会这样?为什么不能emplace_back优化 strlen在这里打电话?我最初的想法是 push_back正在隐式创建 std::string 函数调用之前(因此 std::string 构造函数直接传递字符串文字,这是最佳处理方式),而 emplace_back创建 std::string 函数调用之后(因此 std::string 构造函数被转发 字符串文字,我认为它已经从 const char [N] 衰减到 const char *,因此需要一个strlen 电话)。

但是 emplace_back takes a T&& parameter , 和 my tests show that the string literal shouldn't be decaying to a pointer here .显然我忽略了一些东西。

最佳答案

strlen 调用在慢路径的外联函数体中;该函数体必须对 const char (&)[42] 类型的所有参数有效(在您的 godbolt 示例中),包括并非源自 41 个字符的字符串文字且没有嵌入空值的参数.

快速路径内联到 foo 中,它会在编译时计算长度。

关于c++ - 为什么 emplace_back ("Hello") 调用 strlen?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51219755/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com