禁止在栈中初始化的类【2】

来源:互联网 发布:java array.tostring 编辑:程序博客网 时间:2024/06/03 12:03

    将构造和析构设置为private,即可禁止栈中实例化。如果用protected,则可以被继承。

   

// 禁止在栈中实例化。那就只有在堆中实例化喽?// 在栈中实例化需要干嘛呢?构造和析构。将其中之一设为private即可。// 然后就是单件模式的套路了~在成员函数中提供接口,执行new和delete操作。// PS:将构造和析构设计为私有,同时也就禁止了继承。// 但是如果设计为protected可以实现继承,不过会不会留下隐患?子类可以使用共有构造和析构函数,这样可以拥有父类的行为#include <iostream>using namespace std;class S   // 标准单件模式1{public:    static S* get_instance()    {        if(sp) return sp;        else   return (sp=new S);    }    void print(){cout<<"It is S"<<endl;}    void destroy()    {        delete this;    }private:    static S*sp;    S(){cout<<"S::ctor"<<endl;}    ~S(){cout<<"S::dector"<<endl;}};S* S:: sp=0;class S2   // 标准单件模式2{public:    static S2* get_instance()    {        static S2 s;        return &s;    }    void print(){cout<<"It is S2"<<endl;}    void destroy()    {        ;    }private:    S2(){cout<<"S2::ctor"<<endl;}    ~S2(){cout<<"S2::dector"<<endl;}};// 构造和析构声明为protected,这样禁止在栈中构造,但是不影响继承。class Parent{public:    void print(){cout<<"It is Parent"<<endl;}protected:    Parent(){cout<<"Parent::ctor"<<endl;}    ~Parent(){cout<<"Parent::dector"<<endl;}};class child:public Parent   // child中除了共有的构造和析构以外什么也没有{public:    child(){cout<<"child::ctor"<<endl;}        ~child(){cout<<"child::dector"<<endl;}    };int main(){    {        S*p= S::get_instance();  // 用指针的单件模式        p->print();        p->destroy();    }    cout<<endl<<endl;    {        S2*p= S2::get_instance();  //用static变量的单件模式        p->print();    }       cout<<endl<<endl;        child chld;                   // 继承之后,等效于在栈中实例化了Parent    Parent &rp=chld;    rp.print();    return 0;}

chen@chen-book1:~$ g++ heap_only.cpp -o heaponlychen@chen-book1:~$ ./heaponly S::ctorIt is SS::dectorS2::ctorIt is S2Parent::ctorchild::ctorIt is Parent                  // !!!!child::dectorParent::dectorS2::dectorchen@chen-book1:~$ 



原创粉丝点击