此代码编译并执行。我知道在第一种情况下我们有未定义的行为。但是在第二种情况下到底发生了什么?
#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/