gpt4 book ai didi

c++ - 参数评估与链式方法之间是否存在保证发生之前的关系?

转载 作者:搜寻专家 更新时间:2023-10-31 01:17:39 28 4
gpt4 key购买 nike

我想用这段代码在 C++ 中修剪一个字符串:

std::string str("  Trim test   ");
str.erase( /* 1 */
0, /* 2 */
str.find_first_not_of(" ") /* 3 */
) /* 4 */
.erase( /* 5 */
str.find_last_not_of(" ") + 1, /* 6 */
std::string::npos /* 7 */
); /* 8 */

标准是否允许在执行第 1 行之前计算第 6 行,以便最终调用第 5 行时,参数可能不再有效?

最佳答案

是的,标准允许在执行第 1 行之前计算第 6 行。

来自 the Wikipedia page on sequence points :

[Sequence points occur] Before a function is entered in a function call. The order in which the arguments are evaluated is not specified, but this sequence point means that all of their side effects are complete before the function is entered. In the expression f(i++) + g(j++) + h(k++), f is called with a parameter of the original value of i, but i is incremented before entering the body of f. Similarly, j and k are updated before entering g and h respectively. However, it is not specified in which order f(), g(), h() are executed, nor in which order i, j, k are incremented. Variables j and k in the body of f may or may not have been already incremented. Note that a function call f(a,b,c) is not a use of the comma operator and the order of evaluation for a, b, and c is unspecified.

你应该把它重写为

str.erase(0, str.find_first_not_of(" "));           

str.erase(str.find_last_not_of(" ") + 1, std::string::npos);

关于c++ - 参数评估与链式方法之间是否存在保证发生之前的关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7909550/

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