简体   繁体   English

从函数返回对对象的静态const引用

[英]Returning static const reference to object from functions

In Effective C++ (Item 18: Make interfaces easy to use correctly and hard to use incorrectly), I saw a code sample similar to the following: 在有效的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));

Are there any drawbacks of changing the functions so that they return static const reference to Month? 更改函数以使它们将静态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;
};

I thought the second version is a bit more efficient than the first one. 我认为第二个版本比第一个版本有效。

Reason 1: It's not better. 原因1:并不好。

Returning by value incurs the cost of copying the entire object. 按值返回将导致复制整个对象的成本。

Returning by reference incurs the cost of copying what's effectively a pointer, plus the cost of dereferencing that pointer. 通过引用返回将产生复制有效指针的开销,以及取消引用该指针的开销。

Since Month is the size of an int : 由于Month是一个int的大小:

  • Copying a reference is no faster than copying a Month 复制参考资料并不比复制Month
  • Dereferencing would be incurred every time that reference is accessed. 每次访问引用都会导致取消引用。

So in general, returning by const reference is an optimization chosen to prevent what would be a costly copy. 因此,通常来说,通过const引用返回是一种优化选择,可避免产生昂贵的副本。

Reason 2: static makes it worse 原因2: static会使情况更糟

Unlike C, C++ promises that a static variable in a function will be constructed at the time of the function's first call. 与C不同,C ++承诺在函数的首次调用时将构造函数中的静态变量。

In practice this means that every call to the function must begin with some unseen logic to determine if it's the first call. 实际上,这意味着对函数的每次调用都必须以一些看不见的逻辑开始,以确定它是否是第一次调用。

See also Vaughn Cato's answer 另请参阅沃恩·卡托(Vaughn Cato)的答案

See also ildjam's comment 另请参阅ildjam的评论

某些编译器不会内联包含静态局部变量的方法,而内联是此处最重要的性能优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM