【C++学习】对私有构造析构函数的思考:new一个类对象vs直接创建类对象
前置知識:
new的類對象需要手動delete。且使用堆空間。且只能用指針接收。
直接創建的類對象創建在棧中(或說堆棧)。不需要手動delete,隨著生存周期的結束(如所在的函數return了)而釋放,和堆棧空間一起釋放了。
為什么要私有構造函數?
把析構函數定義為私有的,就阻止了用戶在類域外對析構函數的使用。這表現在如下兩個方面: ??
????
??1. ??禁止用戶對此類型的變量進行定義,即禁止在棧內存空間內創建此類型的對象。要創建對象,只能用 ??new ??在堆上進行。 ??
????
??2. ??禁止用戶在程序中使用 ??delete ??刪除此類型對象。對象的刪除只能在類內實現,也就是說只有類的實現者才有可能實現對對象的 ??delete,用戶不能隨便刪除對象。如果用戶想刪除對象的話,只能按照類的實現者提供的方法進行。 ??
????
??可見,這樣做之后大大限制了用戶對此類的使用。一般來說不要這樣做;通常這樣做是用來達到特殊的目的,比如在 ??singleton(單例模式)? ?的實現上。
私有構造函數,私有析構函數的幾個例子:
?注意這里getInstance的實現不能保證單例。
例1
#include <iostream>using namespace std; class A {public:static A* getInstance() { return new A; }void Distroy() { delete this; }private:A() { cout << "construct A" << endl; }~A() { cout << "xigou A" << endl; } }; int main() {A* a_ptr = new A;return 0; }報錯:
error: calling a private constructor of class 'A'
例2
#include <iostream>using namespace std; class A {public:static A* getInstance() { return new A; }void Distroy() { delete this; }private:A() { cout << "construct A" << endl; }~A() { cout << "xigou A" << endl; } }; int main() {A a;return 0; }報錯
error: calling a private constructor of class 'A'
error: variable of type 'A' has private destructor
例3
#include <iostream>using namespace std; class A {public:static A* getInstance() { return new A; }void Distroy() { delete this; }public:A() { cout << "construct A" << endl; }private:~A() { cout << "xigou A" << endl; } }; int main() {A a;return 0; }報錯:
error: variable of type 'A' has private destructor
?記住析構函數不能重載,所以沒法既定義public的也定義private的。
例4
#include <iostream>using namespace std; class A {public:static A* getInstance() { return new A; }void Distroy() { delete this; }public:A() { cout << "construct A" << endl; }private:~A() { cout << "xigou A" << endl; } }; int main() {A* a_ptr = new A;return 0; }正常輸出:
construct A
例5:
#include <iostream>using namespace std; class A {public:static A* getInstance() { return new A; }void Distroy() { delete this; }private:A() { cout << "construct A" << endl; }~A() { cout << "xigou A" << endl; } }; int main() {A* a_ptr = A::getInstance();a_ptr->Distroy();//這句沒有也可以正常編譯,因為對象是new出來的,所以需要手動delete!return 0; }正常輸出:
construct A
xigou A
參考鏈接:
https://blog.csdn.net/koudaidai/article/details/7546661
總結
以上是生活随笔為你收集整理的【C++学习】对私有构造析构函数的思考:new一个类对象vs直接创建类对象的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 银行开始年末揽储冲刺,花式揽储层出不穷,
- 下一篇: 申请信用卡哪个银行比较容易 不想被拒卡的