c – 删除指针的责任是什么?

前端之家收集整理的这篇文章主要介绍了c – 删除指针的责任是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我常常想知道,

我知道我可以使用new关键字创建一个指向对象实例的指针,同时将相同的指针作为参数传递给函数.就像我在下面的示例中给出的Animation :: newFrame函数一样.

但是,我也知道作为一般规则,我负责在使用new创建的东西上调用delete.

所以当我像这样调用Frame的构造函数时:

Frame* myFrame
    = new Frame(new point(0,0),new point(100,100),new point(50,20));

在上面的函数调用中使用new创建的3个点最终释放内存的责任在哪里?

毕竟,以上3个新点并没有完全具有我的名字来调用删除.

我总是假设它们属于它们被调用函数的范围,并且它们将简单地超出函数的范围.然而,最近我一直在想也许不是这样.

我希望我在这里已经足够清楚了.

提前致谢,

家伙

struct Frame
    {
    public:
        point f_loc;
        point f_dim;
        point f_anchor;

    //the main constructor:: Creates a frame with some specified values
        Frame(point* loc,point* dim,point* anchor)
        {
            f_loc = loc;
            f_dim = dim;
            f_anchor = anchor;
        }

    };

struct Animation
    {
    public:
        vector<Frame*> frameList;

    //currFrame will always be >0 so we subtract 1
        void Animation::newFrame(int &currFrame)
        {
            vector<Frame*>::iterator it;//create a new iterator
            it = frameList.begin()+((int)currFrame);//that new iterator is 

                    //add in a default frame after the current frame
            frameList.insert(
                        it,new Frame(
                            new point(0,20)));

            currFrame++;//we are now working on the new Frame

        }

        //The default constructor for animation. 
        //Will create a new instance with a single empty frame
        Animation(int &currFrame)
        {
                frameList.push_back(new Frame(
                    new point(0,new point(0,0)));

                currFrame = 1;
        }
    };

编辑:我忘了提到这个问题纯粹是理论上的.我知道有更好的替代原始指针,如智能指针.我只想加深对常规指针的理解以及如何管理它们.

上面的示例也取自我的一个项目,实际上是C / cli和c混合(托管和非托管类),因此这就是为什么构造函数只接受point *而不是通过值(point).因为point是一个非托管结构,因此在托管代码中使用时,必须由我自己,程序员管理. 原文链接:https://www.f2er.com/c/117437.html

猜你在找的C&C++相关文章