使用常量引用作为返回类型
Use of constant reference as return type
我正在阅读Meyer的Effective C++,在第一部分中有一个函数定义:
template<class T>
inline const T& max(const T& a, const T& b)
{ return a > b ? a : b; }
为什么不直接返回T?为什么常数T&?
如果T
是一个大型或复杂的类型,那么您可能不希望复制它的成本按值返回。如果它不可复制,那么它就根本无法按值返回。
返回引用使调用者可以选择是否复制引用;尽管(如注释中所述)如果在调用函数的语句末尾之后保留引用,并且其中一个参数是临时的,则需要小心。
参数是const T &
,因此此函数返回其中一个参数,这正是max
函数应该做的。没有理由返回副本。
至少有两个原因。
创建将返回的临时对象可能是一个常量操作。
另一个原因是,有时您需要访问其中一个参数的左值。例如,考虑代码
#include <iostream>
#include <algorithm>
class A
{
private:
static size_t count;
size_t mID;
public:
A() : mID( ++count ) {}
A( const A & ) : mID( ++count ) {}
size_t getID() const { return mID; }
};
bool operator <( const A &a1, const A &a2 )
{
return a1.getID() < a2.getID();
}
size_t A::count;
inline A my_max( const A &a, const A &b )
{
return a < b ? b : a;
}
int main()
{
A one;
A two;
std::cout << std::max( one, two ).getID() << std::endl;
std::cout << my_max( one, two ).getID() << std::endl;
return 0;
}
输出
2
3
我认为3不是你所期望的。
相关文章:
- 将返回类型专用化为 void 或 const 左值引用
- 对于具有引用返回类型的搜索算法,默认返回值应该是什么?
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 将成员函数的返回类型引用到C++中的自定义类
- 具有引用返回类型的重写方法上的协变返回类型无效
- 直接在 C++ 中将值分配给引用返回类型
- 为什么作为返回类型的右值引用不能初始化非常量引用?
- std::function 中不允许引用返回类型吗?
- 为什么类的赋值运算符的返回类型通常是非常量(而不是常量)引用?
- 自动返回类型不推断引用
- 为什么 C++ 从推断的返回类型中去除引用限定符,为什么生存期延长不起作用?
- 为什么返回非引用类型的函数表达式被认为是prvalues而不是xvalues
- 返回对特定尺寸数组的引用,而无需明确说明返回类型中的大小
- 是否可以通过从lambda的引用中返回T型对象,而无需使用尾随返回类型语法
- 从具有引用返回类型的函数返回什么
- 如何推断以引用为参数的函数的返回类型
- 字符串和引用返回类型 C++?
- 模板引用折叠正在删除常量引用返回类型的cv限定符
- 与返回类型(引用、常量引用)混淆
- 为什么返回类型引用输出流