引用在 c++ 中总是更好的选择

Is reference always a better choice in c++

本文关键字:更好 选择 c++ 引用      更新时间:2023-10-16
std::set<BigObject> set;
auto it = set.begin();
auto& it = set.begin();

同样地

std::string str("xxxxxxxxx");
std::string sub = str.substr(xx);
std::string& sub = str.substr(xx);

使用引用调用的时间分解器会减少吗?为什么呢?

当适用且您可以负担得起复制时,按值是最佳选择。

原因是值语义很容易理解(行为像int(,并且比引用和指针更不容易出错。

优化

器在处理指针和引用时很难,因为它们可以别名(指向相同的对象(,或者可以从其他线程引用这些对象,因此无法应用一些重要的优化。参见Chandler Carruth:优化C++的涌现结构了解更多细节。