c++ - 短路临时生命周期

标签 c++

假设我们有一个短路的 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/

相关文章:

c++ - 输入数据类型检查循环未按预期工作 (C++)

c++ - Alpine 图像 standard_init_linux.go :207: exec user process caused "no such file or directory"

c++ 格式无序映射与 fmt::join

c++ - 在 C++ 的 SFML 中居中​​形状/对象

c++ - Dev C++ 在运行大内存程序时崩溃

c++ - 递归函数导致栈溢出

c++ - 可搜索输入过滤器定义

c++ - HTTP 流服务器 : threads?

c++ - Visual Studio Express 显示错误 : "internal error occured in compiler"

c++ - 随机分段故障