gpt4 book ai didi

c++ - 精炼表达式评估(提案 n4228 c++ 17)

转载 作者:行者123 更新时间:2023-11-30 05:25:53 25 4
gpt4 key购买 nike

阅读提案 n4228 我读到以下代码:

void f()
{
std::string s = "but I have heard it works even if you don't believe in it";
s.replace(0, 4, "").replace(s.find("even"), 4, "only").replace(s.find(" don't"), 6, "");
assert(s == "I have heard it works only if you believe in it");
}

受未指定的评估顺序约束,其漏洞最近才被工具发现。

问题出在哪里?也许 s.find("even")s.find("don't") 的计算顺序与任何方面不同?在任何替换发生之前?

有人知道发现问题的工具是什么吗?

最佳答案

是的,你是对的。根据 C++-pre-17 的规则,对 s.find 的两次调用可以在 任何 替换调用之前执行。由于替换调用会修改字符串,因此它们会导致 find 返回的索引在使用时不再有效。

投票进入 C++17 CD 的(不幸的是较弱的)规则将阻止这种情况,并且代码将按预期工作。

关于c++ - 精炼表达式评估(提案 n4228 c++ 17),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38047874/

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