簡體   English   中英

cpp文件中的內聯構造函數和析構函數

[英]inline constructor and destructor in cpp file

聽起來好像很奇怪,我的意思是,當僅在cpp文件中定義一個類時,因為它更多地是用於實現另一個類的幫助程序類,因此不應該放在其私有部分中。 我知道內聯構造函數和析構函數是一種不好的做法,但是這種情況如何呢? 非常感謝你

編輯:我應該改寫它。 在某些情況下,內聯構造函數和析構函數會意外導致膨脹代碼(如有效C ++項目30“了解內聯的來龍去脈”中所述)。 但是我想知道這種內聯是否也導致了這種情況

    // my_class.cpp
    #include <my_class.h>

    namespace {
        class Helper
        {
            public: 
                Helper() {...} // should I inline the constructor here?
                ~Helper() {...} // should I inline the destructor here? 
        };

        /* alternative implementation looks like
        Helper::Helper()
        {...}

        Helper::~Helper()
        {...}
        */
    } // end of anonymous namespace

    // implementation of my_class

這可能是有爭議的。 這里的另一個討論很大程度上對此進行了討論。 基本的好處是,編譯器可以忽略您的“內聯”,也可以選擇在沒有您輸入的情況下“內聯”函數/構造函數/任何內容。 內聯命令只是建議編譯器可以忽略。

TL; DR加油! 它可能不會有所作為。

無論哪種方式都很好。 如果輔助函數由於沒有被內聯而成為性能瓶頸,那么您可以考慮使其成為內聯函數。

很多時候,我發現Helper類的單個實例足以供主類使用。 因此,構造函數和析構函數是否內聯根本沒有任何區別。

namespace {
    class Helper
    {
        public: 
            Helper() {...}
            ~Helper() {...}
    };

    // The sole instance of the Helper class.
    static Helper helper;
}

void main_class::foo()
{
   helper.foo();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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