[英]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
無論哪種方式都很好。 如果輔助函數由於沒有被內聯而成為性能瓶頸,那么您可以考慮使其成為內聯函數。
很多時候,我發現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.