如何限制一個類對象只在堆上分配或者只在棧上分配?

引用自

http://blog.csdn.net/wonengxing/article/details/6862971


1 在C++中如何限制一個類對象只在堆上分配?
仿照設計模式中的單實例模式或者工廠模式來解決,這裏採用單實例模式方式來說明。
將類的構造函數屬性置爲private,同時提供static成員函數getInstance,在函數中new一個新對象,然後返回對象指針或者引用。這樣實現的類可以保證只可以在堆上分配對象。

2 在C++中如何限制一個類對象只在棧上分配?
重載類的new操作符,使重載後的new操作符的功能爲空。這樣就使外層程序無法在堆上分配對象,只可以在棧上分配。


測試代碼如下:

#include <stdio.h>
#include <malloc.h>
#include <assert.h>


//
// void   *   operator   new(size_t   size)
// {
//     printf("調用全局new\n");
//     void   *p   =   malloc(size);
//     return   (p);
// }
// void   *   operator   new[](size_t   size)
// {
//     printf("調用全局new[]\n");
//     void   *p   =   malloc(size);
//     return   (p);
// }
// void   operator   delete(void   *p)
// {
//     free(p);
//     printf("調用全局delete\n");
// }
//
// void   operator   delete[](void   *p)
// {
//     free(p);
//     printf("調用全局delete[]\n");
//     
// }


class stackonly
{
private:
    void * operator new(size_t Size)
    {
        printf("stackonly調用重載new\n");
        return malloc(Size);
    }
    void * operator new[](size_t Size)
    {
        printf("stackonly調用重載new[]\n");
        return malloc(Size);
    }
    void   operator   delete(void   *p)
    {
        free(p);
         printf("stackonly調用重載delete\n");

        
    }
    void   operator   delete[](void   *p)
    {
         free(p);
         printf("stackonly調用重載delete[]\n");
        
    }
public:
    stackonly():a(-1),b(-1),c(-1){printf("stackonly調用構造函數\n");}
    ~stackonly(){printf("stackonly調用析構函數\n");}
    void print(){printf("%d %d %d\n",a,b,c);}
public:
    int a;
    int b;
    int c;
};


class heaponly
{
private:
    heaponly():a(-2),b(-2),c(-2){printf("heaponly調用構造函數\n");}
    ~heaponly(){printf("heaponly調用析構函數\n");}
public:
    static heaponly* GetInstance();    //單件模式
    static void ReleaseInstance();//釋放實例引用
    void print(){printf("%d %d %d\n",a,b,c);}
private:
    int a;
    int b;
    int c;
    static int refCount;

public:
    static heaponly *hp;
};

heaponly* heaponly::hp = NULL;
int heaponly::refCount = 0;

heaponly* heaponly::GetInstance()
{
    if (hp == NULL)
    {
        hp =new heaponly;
        assert(hp);
    }
    ++refCount;
    return hp;    
}

void heaponly::ReleaseInstance()
{
    if (refCount == 0)
    {
        return;
    }

    --refCount;
    if (0 == refCount)
    {
        delete hp;
        hp =NULL;
    }    
}

void main()
{
    stackonly stackOnly;
    stackOnly.print();
    //stackonly *p= new stackonly;//編譯報錯
    //heaponly hep;//編譯報錯
    heaponly *pHeapOnly = heaponly::GetInstance();
    pHeapOnly->print();

    heaponly *pAnother =heaponly::GetInstance();
    pAnother->print();

    pHeapOnly->ReleaseInstance();
    pAnother->ReleaseInstance();    
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章