std::ostringstream not initialized with std::string

63 views Asked by At

I tried to initialize a std::ostringstream with a const std::string but the string returned by the str() method does not include the initial string. I compile with a company toolchain based on gcc-4.3.2 with C++11 enabled.

Example

#include <sstream>

const std::string str = "foo";
const std::string longStr = "barbarbar";

int main() {
  std::ostringstream ss1(str);
  std::ostringstream ss2{str};
  std::ostringstream ss3;
  ss3 << str;

  ss1 << longStr;
  ss2 << longStr;
  ss3 << longStr;

  std::cout << ss1.str() << std::endl;
  std::cout << ss2.str() << std::endl;
  std::cout << ss3.str() << std::endl;
}

Result

barbarbar
barbarbar
foobarbarbar

I expected all three lines to be equal, but only the ss3 solution provided the right result. I tried this code on code.sh and it did what was expected: concatenating str and longStr.

I found a similar situation here without much explanations on why it behaves that way: std::ostringstream overwriting initializing string

Why are the two first initializations not providing the expected result in my case? What can make std::ostringstream behave differently in different compilation contexts?

0

There are 0 answers