Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<< operator vs. overloaded + operator for strings in C++

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";
like image 819
J-Win Avatar asked Mar 23 '26 22:03

J-Win


1 Answers

Yes:

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.

like image 106
user975989 Avatar answered Mar 25 '26 12:03

user975989



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!