为什么c_str()为两个不同的字符串返回相同的值?

Jas*_* Tu 4 c++ string

给定一个简单的文件加载功能,

std::string load_file(const std::string &filename) {
    std::ifstream     file(filename);
    std::string       line;
    std::stringstream stream;
    while (std::getline(file, line)) {
        stream << line << "\n";
    }
    return stream.str();
}
Run Code Online (Sandbox Code Playgroud)

为什么以下打印another_file两次内容?

const char *some_file = load_file("some_file").c_str();
const char *another_file = load_file("another_file").c_str();
printf("%s", some_file);
printf("%s", another_file);
Run Code Online (Sandbox Code Playgroud)

Dav*_*nan 14

代码坏了.您正在调用c_str()立即销毁的临时对象.这意味着返回的值c_str()无效.

您需要确保std::string返回的对象至少在您保持调用返回的指针时保持不变c_str().例如:

std::string some_file = load_file("some_file");
std::string another_file = load_file("another_file");
printf("%s", some_file.c_str());
printf("%s", another_file.c_str());
Run Code Online (Sandbox Code Playgroud)