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";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With