简体   繁体   English

动态分配内存(指针数组)

[英]Dynamic allocation of memory (Array of pointers)

is there a memory leak in this operator overloading ? 此运算符重载中是否存在内存泄漏?

My thinking is below the code.. (MotorVehicle is a class with no allocation) 我的想法在代码下面。(MotorVehicle是一个没有分配的类)

class myClass{    
private:
    MotorVehicle **vehicle;
    int vehNo;
public:

myClass() : vehicle(), vehNo(0){ } // vehicle() -> NULL

    ~myClass()
    {
        for(int i = 0; i < vehNo; i++)
            delete vehicle[i];
    }
    .
    .
    .
    myClass &operator+=(MotorVehicle *veh)
    {
        MotorVehicle **temp = new MotorVehicle*[vehNo + 1];
        for(int i = 0; i < vehNo; i++)
            temp[i] = vehicle[i];
        temp[vehNo] = veh;
        //for(int i = 0; i < vehNo; i++)
          //  delete vehicle[i];
        vehNo++;
        vehicle = new MotorVehicle*[vehNo];
        for(int i = 0; i < vehNo; i++)
            vehicle[i] = temp[i];

        return *this;
    }
};

I have array of pointers of type MotorVehicle (**tmp) for which I have allocated memory and set every single one of them to point to what a vehicle is pointing to + last one to point to what veh was pointing to. 我有一个类型为MotorVehicle(** tmp)的指针数组,已为其分配内存,并将它们中的每个指针设置为指向车辆指向的对象,最后一个指向指向veh指向的对象。 Since I set them to point to what vehicle was pointing I wont lost the data somewhere and can deallocate them in the future. 由于我将它们设置为指向车辆指向的位置,因此我不会在某处丢失数据,并且将来可以重新分配它们。 Then I allocated memory for vehicle again to return them to point to +1 object. 然后,我再次为车辆分配了内存,以使其返回指向+1对象的位置。 However I'm allocating memory two times and both contain the location of same thing, so If i delete one of them then the other won't have anything in it (will hang somewhere).. But at the end the memory will get deleted with the destructor ? 但是我要分配内存两次,并且都包含同一事物的位置,因此,如果我删除其中一个,则另一个将没有任何内容(将挂在某处)。但是最后,内存将被删除与破坏者? Am I thinking right? 我在想对吗? How to get around allocating memory 2 times for the same thing? 如何避免为同一件事分配2次内存?

Ps yeah manually :# (Any materials which might help me in any way would be greatly appreciated) ps是的:#(任何可能以任何方式帮助我的材料将不胜感激)

Yes, you're leaking temp . 是的,您正在泄漏temp

A better try: 更好的尝试:

myClass &operator+=(MotorVehicle *veh)
{
    MotorVehicle **temp = new MotorVehicle*[vehNo + 1];
    for(int i = 0; i < vehNo; i++)
        temp[i] = vehicle[i];
    temp[vehNo] = veh;
    vehNo++;
    delete[] vehicle;
    vehicle = temp;

    return *this;
}

An even better solution: Use std::vector . 更好的解决方案:使用std::vector

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

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