前置知识:
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