1
このコードでyを読んだあと、text1の値が変わるのはなぜですか?ostringreader.str()を保存しないでください。c_str()
void func()
{
int value1 = 5;
double value2 = 1.5;
std::ostringstream x, y;
x << value1;
y << value2;
const char *text1 = x.str().c_str();
fprintf(stderr, "text1: v=%s, p=%p\n", text1, &text1);
const char *text2 = y.str().c_str();
fprintf(stderr, "text1: v=%s, p=%p\ntext2: v=%s, p=%p\n", text1, &text1, text2, &text2);
}
出力:
テキスト1:V = 5、= 0xbfcfd508
テキスト1:V = 1.5、= 0xbfcfd508
テキスト2:V = 1.5、A = 0xbfcfd510
ストーリーの道徳:特にc_str()を避ける –
[c_str](http://www.cplusplus.com/reference/string/string/c_str/)の戻り値は有効であることが保証されていますオブジェクトに対する次の非const操作まで。デストラクタは非constです。したがって、使用する前に無効になった結果を保存しています。 –
ありがとうございました!あなたがそれのようにそれを綴るとき、それは明らかです。 – Civing