"C++中的字符串的运算符与重载+运算符"

J-W*_*Win 3 c++ performance operators

以下两行代码之间是否有区别?

(也许是效率或某种性质?)

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

std::cout << a << " comes before " << b << "\n";
std::cout << a + " comes before " + b + "\n";
Run Code Online (Sandbox Code Playgroud)

use*_*989 10

是:

第一行调用operator<<std::cout(的类型std::ostream).它打印每个操作数.

第二行调用operator+std::string,它创建多个临时std::string对象然后最终调用operator<<它打印它们.

首选因为它避免了临时对象,并且效果更好.考虑情况是ab有类型int.第一个版本继续工作,第二个版本将不再有效.