-1

我不知道我是否应该创建一个析构函数来删除Controller设置为由 main 传递的参数的成员,这些参数是动态创建的,因为构造函数从未使用new关键字来设置它们。

int main()  
{
    int numCars = 3;
    int numPlanes = 3;
    Machine *car= new Car[numCars];
    Machine *plane = new Plane[numPlanes];

    Controller *control = new Controller(car, plane);

    delete control;
    return 0;
}

class Controller
{
public:
    Controller(Machine *car, Machine *plane);
//Would I need to make a destructor 
//~Controller();
private:
    Machine *car;
    Machine *plane;
Controller :: Controller(Machine *car, Machine *plane)
{
    this->car = car;
    this->plane = plane;
    changeCarandPlane();
}
//destructor
//    Controller :: ~Controller()
//   {
//    delete[] car;
//    delete[] plane;
//    }
};
4

3 回答 3

2

不,您不应该在析构函数中删除。main似乎拥有分配的数组,所以从main.

int main()  
{
    int numCars = 3;
    int numPlanes = 3;
    Machine *car= new Car[numCars];
    Machine *plane = new Plane[numPlanes];

    Controller *control = new Controller(car, plane);

    delete control;
    delete [] plane;
    delete [] car;
    return 0;
}

如果要在Controller析构函数中删除,则必须确保没有两个实例Controller指向相同的动态分配的Machine数组。

您应该考虑使用std::vector<Machine>而不是动态分配的数组,或者至少使用一些范围保护来保证删除。

#include <vector>
int main()  
{
    const int numCars = 3;
    const int numPlanes = 3;
    std::vector<Machine> cars(numCars); // holds 3 default constructed Machines
    std::vector<Machine> planes(numPlanes); // holds 3 default constructed Machines

    Controller control(cars, planes);
}
于 2012-11-18T17:43:32.080 回答
0

在好的设计中,创建对象的实体通常也负责释放它。鉴于此,要么从控制器构造函数中释放内存,要么main()在控制器构造函数中分配内存,然后在控制器析构函数中释放 - 选择取决于实际要求。

于 2012-11-18T17:45:47.737 回答
0

那么如何使用共享指针呢?

#include <memory>

class Machine {};
class Car : public Machine{};
class Plane : public Machine{};

template<typename T>
struct ArrayDeleter
{
   void operator()(T* p)
   {
      delete [] p;
   }
};

class Controller
{
public:
    Controller(std::shared_ptr<Car> cars, std::shared_ptr<Plane> planes)
    {}
};

int main()  
{
    int numCars = 3;
    int numPlanes = 3;
    std::shared_ptr<Car> cars(new Car[numCars], ArrayDeleter<Car>());
    std::shared_ptr<Plane> planes(new Plane[numPlanes], ArrayDeleter<Plane>());

    Controller *control = new Controller(cars, planes);

    delete control;
    return 0;
}
于 2012-11-18T19:12:46.750 回答