Kishimo
Kishimo

Reputation: 93

C++ string.c_str()

If using g++ and clang++, I get ++my string==my string##my string--. While MSVC and Intel Compiler, it is ++==my string##my string--.

Why?

#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;
}

Is it an undefined behavior?

Upvotes: 1

Views: 810

Answers (1)

R Sahu
R Sahu

Reputation: 206557

In a comment, you asked:

Why test().c_str() can work but s1 not?

test().c_str() works only in some contexts, not all contexts.

std::cout << test().c_str() << std::endl;

is guaranteed to work since the temporary returned by test() is required to stay alive until the execution of the statement is complete.

On the other hand,

char const* s1 = test().c_str();
std:cout << s1 << std::endl;

is undefined behavior since the temporary is not required to live beyond completion of execution of the first line.

Upvotes: 8

Related Questions