我不知道是否应该创建一个析构函数来删除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;
// }
};
答案 0 :(得分: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);
}
答案 1 :(得分:0)
在良好的设计中,通常创建对象的实体也负责释放它。鉴于此,要么从main()
释放内存,要么在控制器构造函数中分配并在控制器析构函数中释放 - 选择取决于实际要求。
答案 2 :(得分: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;
}