Is there is difference between the two following lines of code?

(Perhaps in efficiency or something of that nature?)

const std::string a = "a";
const std::string b = "b";

std::cout << a << " comes before " << b << "\n";
std::cout << a + " comes before " + b + "\n";
  • 1
    I'd gues it's compiler dependent, but the first one would simply be the equivalent of output a; output string; output b; output string and the second is create string a, concatenate a string, concatenate var b, concatenate string, output completed string – Marc B Jul 18 '16 at 20:19
  • Yes. There is a difference. – Edward Strange Jul 18 '16 at 20:22


The first line calls operator<< of std::cout (of type std::ostream). It prints each of its operands.

The second line calls operator+ of std::string, which creates multiple temporary std::string objects which then eventually call operator<< which prints them.

Prefer the first because it avoids temporary objects, and works better. Consider the situation were a and b have type int. The first version continues to work the second will no longer work.

Your Answer

