相关疑难解决方法(0)

什么时候在函数调用中发生临时对象的破坏?

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

#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 …
Run Code Online (Sandbox Code Playgroud)

c++

9
推荐指数
2
解决办法
535
查看次数

标签 统计

c++ ×1