以下两行代码之间是否有区别?
(也许是效率之类的?)
const std::string a = "a";
const std::string b = "b";
std::cout << a << " comes before " << b << "\n";
std::cout << a + " comes before " + b + "\n";
是的:
第一行调用operator<<
的std::cout
(的类型std::ostream
)。它打印每个操作数。
第二行调用operator+
的std::string
,它创建多个临时std::string
对象然后最终调用operator<<
它打印它们。
首选第一个,因为它避免了临时对象,并且效果更好。考虑当时的情况a
和b
类型int
。第一个版本继续工作,第二个版本不再工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句