一.只允许一个对象的生成
每当产生一个对象,就会有一个构造函数被调用,如果“阻止某个class产出对象”,最简单的办法就是将其constructors 声明为private:
#include <iostream>
using namespace std;
将构造函数私有化可以"阻止某个class对象的生成"
法一:建立fried函数可以允许生成唯一的一个class对象
class Print
{
public:
void submitJob()
{
cout<<this<<":Print::submitJob()\n";
}
void reset()
{
cout<<this<<":Print::reset()\n";
}
void performSelfTest()
{
cout<<"Print::performSelfTest()\n";
}
friend Print & thePrint();
protected:
private:
Print()
{
cout<<"Print::Print()\n";
}
Print(const Print &rhs)
{
cout<<"Print::copy Print()\n";
}
};
Print& thePrint()
{
static Print p;
return p;
}
int main() {
thePrint().reset();
thePrint().submitJob();
}
此设计有3个成分:第一.,将Print class 的constructors声明为private,压制对象的产生。第二,全局函数thePrint声明为class的一个friend友元,致使thePrint不受private属性的约束。第三,thePrint函数中内含一个static Print对象,意思是只有一个Print对象会被产生。
书中还有另一种方法,就是将thePrint函数设置为class 的一个static 函数,但是这么做不好,书中声明:“函数拥有一个static对象”比“class拥有一个static对象”的优势在于,“class拥有一个static对象”即使从未被用到,他也会被构造(及析构),而“函数拥有一个static对象”只在函数第一次被调用才产生static对象。
二.pseudo constructor(伪构造函数)
#include <iostream>
#include <memory>
using namespace std;
class Print
{
public:
void submitJob()
{
cout<<this<<":Print::submitJob()\n";
}
void reset()
{
cout<<this<<":Print::reset()\n";
}
void performSelfTest()
{
cout<<"Print::performSelfTest()\n";
}
//pesudo constructor
static Print* makePrint()
{
return new Print();
};
//pesudo copy constructor
static Print* makePrint(const Print &rhs)
{
return new Print(rhs);
};
protected:
private:
Print()
{
cout<<"Print::Print()\n";
}
Print(const Print &rhs)
{
cout<<"Print::copy Print()\n";
}
};
int main() {
//为了避免内存泄露,使用智能指针
auto_ptr<Print> pA(Print::makePrint());
}