views:

231

answers:

4

What is the difference, if any between the effects of the following snippets:

cout << "Some text" << s1 << "some more text\n";

cout << "Some text" + s1 + "some more text\n";
+1  A: 

The second concatenates the strings before sending them to cout, which is a performance hit, potentially quite large with big strings. You always want to use the first form if you can.

chaos
+15  A: 

The result of operator+ on strings is a new string. Therefore, in the example

cout << "Some text" + s1 + "some more text\n";

two new strings are created (implies memory allocation) before the whole thing is written to cout. In your first example, everything is written directly to cout without unnecessary memory allocation.

Whisty
+2  A: 

Yeah, string operator+ (const char* lhs, const string& rhs) creates and returns an unnamed temporary string object.

cout << "Some text" calls ostream& ostream::operator<<( const char* const) and returns the ostream reference.

cout << "Some text" << s1 << "some more text\n";

is ostream::operator<<( "Some text").operator<<(s1).operator<<("some more text\n"), three calls on cout, calling two different overloads of op<<, the op<< that takes a const* char* const and the op<< that takes a const string&. No memory allocations, and the only copying is to cout's buffer.

cout << "Some text" + s1 + "some more text\n";

is ostream::operator<<(t1) on a temporary string object I'll call t1, which t1 is the temporary result from ::operator+ ( "Some text", s1).operator+("some more text\n"). (Note that the first operator+ is not a member of string, but the op+ (const char* const, const string&) at namespace scope. It returns a string, so the second +" is string::operator+( const char* const).)

So two temporary string objects are created (and then destructed), in this code. That means two internal representations for the strings (so two memory allocations) and two copies two that newly allocated memory (in addition to the copying to cout's buffer).

tpdi
+5  A: 

Consider the following:

cout << "Some text" + " " + "some more text\n";

It won't do what you think. Operator+ doesn't always mean concatenate.

Edit: When applied to raw strings, operator+ doesn't concatenate - it adds the addresses of the pointers to the strings. The result is almost guaranteed to be nonsense, because it points to an area of memory that has no relationship to any of the original strings. With luck it will crash your program.

Edit 2: Apparently it has been a very long time since I made this mistake. The results are so nonsensical that the compiler refuses to compile it.

Mark Ransom
Don't be coy Mark, explain it's the addition of two pointers.
tpdi
Yes, please explain further. I tried it and got the error. Why does it happen?
108
You simply cannot add pointers. It doesn't even compile.
MSalters
You would have to cast one of the pointers to an integer first
Greg Rogers