C++ string.c_str()

Kis*_*imo 0 c++ undefined-behavior

如果使用g++clang++,我得到++my string==my string##my string--.虽然是MSVC和英特尔编译器++==my string##my string--.

为什么?

#include <string>
#include <iostream>

using namespace std;

string test()
{
    string s0 = "my string";
    return s0;
}

int main()
{
    string s = test();
    const char* s1 = test().c_str();
    const char* s2 = s.c_str();
    cout << "++" << s1 << "==" << s2 << "##" << test().c_str() << "--" << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是一个未定义的行为吗?

R S*_*ahu 6

在评论中,你问:

为什么test().c_str()可以工作但s1不是?

test().c_str() 仅适用于某些情境,而非所有情境.

std::cout << test().c_str() << std::endl;
Run Code Online (Sandbox Code Playgroud)

保证工作,因为临时返回者test()必须保持活着,直到声明的执行完成.

另一方面,

char const* s1 = test().c_str();
std:cout << s1 << std::endl;
Run Code Online (Sandbox Code Playgroud)

是未定义的行为,因为临时不需要超出完成第一行的执行.