more effective c++ item26 控制对象的数量

#include <iostream>
using namespace std;

//zero object
class CantBeInit{
private:
    CantBeInit();
    CantBeInit(const CantBeInit &);
};

//one objiect
class printer{
public:
    void reset();
    //void submitJob(const printer_job& job);
    void performSelfTest();

    friend printer& ThePrinter();
private:
    printer();
    printer(const printer &);
};

printer& ThePrinter()
{
    static printer p;
    return p;
}
//////////////////////////////
// friend ThePrinter is golble vaule, it is not good 
// so ,make it be a static mem_fcn, it will be (printer::)
//scope

class printer{
public:
    static printer& ThePrinter();//讨论一 A
    //...
};

//////////////////////////////
// also using namespace,maybe better
namespace PrinterStuff{
    class printer{
    public:
        friend printer& ThePrinter();// 讨论一 B
    };
}

/*
    类拥有一个静态对象,就说A,和拥有一个 B(B里有一个static),
    1: 成本,A不管你用不用,他都会被初始化,分布内存,B只有被调用
    时才会被初始化,
    2: 反正Binline的话,会被复制,每次被调用都会被复制一次,说是内部链接
*/
////////////////////////////
// using except way
/*可以随意设定打印机个数,缺点不能继承*/
class printer{
public:
    class TooManyPrinter{};

    printer();
    ~printer();
    //...
private:
    static size_t  numObject;
    printer(const printer &);
};
printer::printer()
{
    if(numObject >= 1)
        throw(TooManyPrinter)
    else
        printer* p = new printer();//I guess
        numObject ++;   
}
printer::~printer()
{
    if(numObject == 0)
        return;
    else
        delete p;
        numObject --;
}
/////////////////////////////////////////////////
//but there are out of our thought happening
//if have a inherface 

class ColorPrinter : public printer{\
public:
    //...
};

printer p;
ColorPrinter cp;

//error happen: derided class object has base class object 
//cp make num_object >1

/*

*/
////////////////////////////////////////////////////
class FSA{
public:
    //pseudo(伪) ctor
    static FSA* makeFSA();
    static FSA* makeFSA(const FSA&);
    //...
private:
    FSA();
    FSA(const FSA& );
};

FSA* makeFSA()
{
    return new FSA();//这样的话,你就要管理指针了
    //所以理所当然想起unique_ptr
}

FSA* makeFSA(const FSA& rhs)
{
    return new FSA(rhs);
}


///////////////////////////////////////////////
// pseudo ctor && num_object

class Printer
{
public:
    void reset();
    //void submitJob(const printer_job& job);
    void performSelfTest();

    class TooManyPrinter{};

    static Printer* makePrinter();
    ~printer();
private:
    static size_t  numObject;
    Printer()
    printer(const printer &);
};
/*把伪ctor 和 控制个数的类 结合*/

猜你喜欢

转载自blog.csdn.net/qq_24328911/article/details/51405717