protected destructor

constructor access modifier 一般設為public,而在singleton中,為了限制生成的物件個數,會將constructor放在private,另外在其他method生成物件。而對於destructor,以Meyers Singleton的實作來說,destructor放在public or non-public皆可,因為static object 在宣告的地方可以存取到private destructor(參考下面12.4)

C++03 std
§3.6.3 Termination
Destructors (12.4) for initialized objects of static storage duration (declared at block scope or at namespace scope) are called as a result of returning from main and as a result of calling exit (18.3).
§12.4 Destructors
A program is ill-formed if an object of class type or array thereof is declared and the destructor for the class is not accessible at the point of the declaration.

ill-formed = not well-formed
well-formed = §1.3.14 a C + + program constructed according to the syntax rules, diagnosable semantic rules, and the One Definition

那麼什麼時候需要用到protected or private destructor呢?

class A
int main()
  A x; // A* x = new A;是可以的
  return 0;

以上編譯時會出現 In function ‘int main()’: error: ‘A::~A()’ is private error: within this context

限制了在stack上生成,而A* x = new A; 則不會有問題,只要不要顯式的在外部呼叫delete
利用factory method返回new 的結果即可

而private destructor 和protected destructor的差別是在當類別有繼承時
在基類的protected destructor可以避免使用者用基類的指標delete

private destructor會使derived class沒辦法delete 或是顯式定義destructor,造成繼承上的困難(除非在derived class不顯式定義destructor)。

This entry was posted in C++ Language. Bookmark the permalink.

Leave a Reply