使用常量引用作为返回类型

Use of constant reference as return type

本文关键字:返回类型 引用 常量      更新时间:2023-10-16

我正在阅读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不是你所期望的。