繁体   English   中英

C ++管理对象的动态分配

[英]C++ managing the dynamic allocation of your objects

我正在尝试实现自己的类Alloc,这将有助于对象的动态分配。

我想跟踪程序中已分配对象的数量。 因此,每次分配对象的新实例时,计数器都会加1,销毁对象时递减。 当我的程序关闭时,如果计数器不为零,则该对象将在屏幕上显示一条错误消息,并使程序挂起,直到用户按下Enter键为止。

到目前为止,这就是我所拥有的..我希望你们能帮助我实现这一目标。

class Alloc{
static int counter;
public:
Alloc(){ counter++; };
Alloc(int *d, static int size, const Alloc& c){

    d=(int *) malloc(size*sizeof(int));;
    //d=new int[size];
    Alloc *my_alloc;
    //my_alloc = new Alloc[size];                //note that the type is a Myclass pointer
    for(int i=0; i<size; i++){
        my_alloc[i] = new Alloc[size];
    }
    //for(int i=0; i < size; i++){
    //    d[i]=c.d[i];
    //}
}
~Alloc(){ counter--; }
};

我知道很多东西不见了,所以,我也将感谢您的帮助和纠正错误。

d=(int *) malloc(size*sizeof(int));;
d=new int[size];

这里的第二行用第二个分配覆盖d指针,因此丢失了malloc分配的malloc

如果您确实想通过这种方式进行操作,则需要使用new放置 ,例如

d=(int *) malloc(size*sizeof(int));;
e=new (d) int[size];

尽管细节很难掌握。


不过,要只计算程序中的对象数量,有一个更简单的选择。 实现一个模板化的“ mixin”,其中包含每种类型的静态计数器。 就像是

    template <typename T>
    struct countable
    {
        countable() { _count++; }
        countable(const countable&) { _count++; }
        ~countable() { _count--; }
        static int get_count() { return _count; }
    private:
        static int _count;
    };

然后让您的对象从中继承,如

    class MyClass : countable<MyClass>
    {
        // whatever
    };

这很简单,并且很容易变成无操作版本发布。

类的实例数的轨迹说,Alloc也可以保留为

class Alloc
{
    Public:
    static int Coounter; // object counter

//  Constructor

    Alloc(){
    Counter++;}

//  Destructor

    ~Alloc()
    {
    Counter--;
    }


};

简单,易用和可维护

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM