① single类中有一个static single对象(非指针);</span></strong>
② single类:私有化构造函数,禁止拷贝构造函数,提供static single& get()
使用时,用single& 接收实例。无需关心实例的析构,因为程序结束时自动调用析构函数销毁所有static对象。
② single类:私有化构造函数,禁止拷贝构造函数,提供static single& get()
使用时,用single& 接收实例。无需关心实例的析构,因为程序结束时自动调用析构函数销毁所有static对象。
#include <iostream>
using namespace std;
class single
{
public:
static single& get(){
return s;
}
~single(){
if(p!=NULL){
delete [] p;
p=NULL;
}
cout<<"deleted!"<<endl;
}
void run(){
cout<<"single instance running!!!"<<endl;
}
private:
static single s;
int * p;
single(){
p=new int[100];
cout<<"allocated!"<<endl;
}
//single& operator = (const single & s);
single(const single & s);
};
single single::s;//必须类外定义
int main() {
single& s1=single::get(); //ok
s1.run();
single& s2=single::get(); //ok
s2.run();
single s3=single::get(); //error 调用拷贝构造函数, private
s3.run();
return 0;
}
测试:http://ideone.com/bgzbRS