簡體   English   中英

從函數返回對對象的靜態const引用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM