假设我们有一个短路的 bool 表达式,例如,
f(g() && std::string().size() == 0);
我正在考虑临时std::string
的生命周期。通常,编译器会在完整表达式的末尾破坏临时变量。但在这种情况下,这是不合适的,因为它不知道 g()
是否返回 true。所以我想知道编译器通常如何处理这种情况。他们是否存储了一个变量来告诉他们是否发出析构函数调用?或者标准是否允许他们提前销毁临时文件?
最佳答案
&&
短路,所以 std::string().size()
只会在 g()
返回真值。 IOW,如果 g()
没有返回 true,则无需担心销毁临时字符串的时间——因为它永远不会首先创建。
例如,给定这样的代码:
#include <iostream>
#include <stdlib.h>
bool g() { return rand() & 1 == 0; }
void f(bool val) {
std::cout << std::boolalpha << val;
}
int main(){
f(g() && std::string().size() == 0);
}
VC++ 生成的代码使用一个临时变量 $T1
来跟踪是否生成了临时变量,并且仅当 $T1
为真时才销毁临时变量,因此序列看起来像这样:
int $T1 = 0
call g()
if (retval == 0)
goto $LN3
call std::string::string()
$T1 = true;
call temp_string.size();
if (retval != 0)
goto $LN3
$TV74 = 1
goto $LN4
$LN3 :
$TV74 = 0
$LN4 :
call f($TV74);
if ($T1 == 0)
goto $LN7
call std::string::~string();
$LN7:
return 0;
在从汇编语言转换回伪代码的过程中,我省略了一些不相关的细节,但保留了原始流程和足够相似的名称,很容易将它们与原始代码进行比较如果你愿意的话。
关于c++ - 短路临时生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19983195/