这段代码会导致UB吗?

mik*_*ike 5 c++

我检查了gcc和clang,两者都没有生成任何警告.我想从foo()临时的生命周期将延长,直到完整表达式结束,这是bar函数调用中的分号所在.

#include <iostream>
#include <string>

struct A
{
    std::string foo() const{ return "aaa"; }
};

void bar(const char* c) {
    std::cout << c;
}

int main()
{
    A a;
    bar(a.foo().c_str()); // Is this safe?
    bar(a.foo().substr().c_str()); // or this
}
Run Code Online (Sandbox Code Playgroud)

Som*_*ken 7

foo()(和substr())返回的临时值将继续存在,直到bar调用结束(方法调用链之后),这是安全的.

int main()
{
    A a;
    bar(a.foo().c_str()); 
    //temporary is destroyed here
    bar(a.foo().substr().c_str()); 
    // and here
}
Run Code Online (Sandbox Code Playgroud)

经典的未定义行为案例:

int main()
{
    A a;
    const char* charPtr = a.foo().c_str();
    printf("%s", charPtr);
}
Run Code Online (Sandbox Code Playgroud)

std::string创建临时,返回指向它的缓冲区的指针,c_str()临时超出范围并被销毁.charPtr现在是一个指向无效位置(死机std::string)的指针.

  • @Trevir:UB 与`a` 发生的事情无关。`foo` 返回的 `std::string` 的生命周期在调用 `printf` 之前结束。(因此`charPtr` 是一个悬空指针)。 (2认同)