c++ - 函数调用中临时对象的销毁究竟发生在什么时候?

标签 c++

此代码编译并执行。我知道在第一种情况下我们有未定义的行为。但是在第二种情况下到底发生了什么?

#include <string>
#include <iostream>
#include <cstdio>

std::string foo() {
    return "HELLO";
}

void bar(const char *p) {
    std::printf("%s\n", p);
}


int main() {

    // FIRST CASE:
    // I know this is bad, because after the assignment
    // the variable returned by foo() is destroyed and we
    // have a bad reference.
    const std::string &s = foo(); 
    bar(s.c_str());


    // SECOND CASE:
    // But what about that ? I don't know exactly if the 
    // object is alive after the call to c_str() 
    bar(foo().c_str());

    return 0;
}

GCC 输出在这两种情况下都是“HELLO”,但我认为那是因为它没有清理原始内存。

在第二种情况下,临时对象到底是什么时候销毁的?

最佳答案

其实这两种情况都可以。

在第一种情况下,将临时对象绑定(bind)到 const 引用会将其生命周期延长至 s 的生命周期。所以它不会被销毁,直到 main 退出。

在第二种情况下,临时对象在包含它的完整表达式结束后被销毁。在这种情况下,它是函数调用。如果您将该 C 字符串存储在任何比 bar 还长的地方,然后尝试访问它,那么您将遇到未定义行为的日期。

关于c++ - 函数调用中临时对象的销毁究竟发生在什么时候?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37946437/

相关文章:

c++ - 如何包含 QwebEngineView 而不会出现错误

c++ - 使用智能指针释放内存

c++ - 包括多个编译单元中的模板代码,它会一直链接而不是内联吗?

c++ - 是否可以在 constexpr 函数中执行 I/O

使用 visual studio 2008 构建 C++ 项目

c++ - 这两种动态扩展数组的方法有什么区别?

带有类对象的 C++ vector push_back

c++ - 在 C++ 中使用右值设置类变量的最有效方法是什么?

c++ - 如何在 C++ 中提取 torch 模型的输出?

c++ - tr1::函数 WINAPI