#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
stringstream s;
s << "Hello";
const char *p = s.str().c_str();
cout << p << endl;
string b = "World";
cout << p << endl;
return 0;
}
#include <string>
#include <iostream>
using namespace std;
int main()
{
stringstream s;
s << "Hello";
const char *p = s.str().c_str();
cout << p << endl;
string b = "World";
cout << p << endl;
return 0;
}
The output of the program is:
Hello
World
World
The second string b shares the same location used by the early retrun of s.str().c_str() and overwrites it. It is unsafe to store the pointer from string::c_str() and use it later because it is an internal location that can be reused by other string objects.
No comments:
Post a Comment