1

In what ways can you use the return values from things like boost::algorithm::join?

std::stringstream ss;
ss<<"quack";
std::cout << ss.str().c_str() << std::endl; // bad idea

This is a bad idea, explained in sbi's comment in https://stackoverflow.com/a/1430774/

std::vector<std::string> v;
v.push_back("foo");
v.push_back("bar");
std::cout << boost::algorithm::join(v,"-").c_str() << std::endl; // what about this?

That made me wonder if this has the same problem?

Could someone give an explanation of the scope of such return values?

Community
  • 1
  • 1
Trygve Flathen
  • 686
  • 7
  • 15

1 Answers1

3

Since you are not storing the reference to the char* there is no problem with both expressions:

From the standard.. http://isocpp.org/std/the-standard

Temporary objects are destroyed as the last step in evaluating the 
full-expression (1.9) that (lexically) contains the point where they
were created. [12.2/3]

So in both cases above you use the char* pointer in the expression. The boost::algorithm::join and stringstream.str() are available till the end of the expression and so is the c_str pointer.

sbi comment in the link you sent referred to taking c_str() from a temporary string in one expression storing it in a const char* and passing that to a C function in a second statement.

Also I usually try use c_str only when calling C style functions or external library functions that require const char*. In the case of an ostream<< it already accepts std::string and it takes 2 sec's to add operator<< functions to support new types.

odedsh
  • 2,594
  • 17
  • 17