[英]Returning static const reference to object from functions
在有效的C ++中(第18项:使接口易于正确使用而难以错误使用),我看到了类似于以下内容的代码示例:
class Month
{
public:
static Month Jan()
{
return Month(1);
}
static Month Feb()
{
return Month(2);
}
//...
static Month Dec()
{
return Month(12);
}
private:
explicit Month(int nMonth)
: m_nMonth(nMonth)
{
}
private:
int m_nMonth;
};
Date date(Month::Mar(), Day(30), Year(1995));
更改函数以使它们将静态const引用返回给Month是否有任何缺点?
class Month
{
public:
static const Month& Jan()
{
static Month month(1);
return month;
}
static const Month& Feb()
{
static Month month(2);
return month;
}
//...
static const Month& Dec()
{
static Month month(12);
return month;
}
private:
explicit Month(int nMonth)
: m_nMonth(nMonth)
{
}
private:
int m_nMonth;
};
我认为第二个版本比第一个版本有效。
原因1:并不好。
按值返回将导致复制整个对象的成本。
通过引用返回将产生复制有效指针的开销,以及取消引用该指针的开销。
由于Month
是一个int
的大小:
Month
快 因此,通常来说,通过const引用返回是一种优化选择,可避免产生昂贵的副本。
原因2: static
会使情况更糟
与C不同,C ++承诺在函数的首次调用时将构造函数中的静态变量。
实际上,这意味着对函数的每次调用都必须以一些看不见的逻辑开始,以确定它是否是第一次调用。
另请参阅沃恩·卡托(Vaughn Cato)的答案
另请参阅ildjam的评论
某些编译器不会内联包含静态局部变量的方法,而内联是此处最重要的性能优化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.