如何正确处理抽象类的抽象成员?

时间:2016-11-03 20:58:39

标签: c++ pointers memory-leaks destructor

我有一个这样的抽象类:

class IMovable {
protected:
    MovementPath *movementPath;

public:
    IMovable();
    virtual ~IMovable();
    void setMovementPath(MovementPath *movementPath);
};

movementPath是其上的抽象类。

当删除IMovable的具体实施时,我需要删除movementPath(更准确地说,就是此时的具体实施)及其任何成员。< / p>

我该怎么做?

我尝试了虚拟析构函数,但是没有用(我可能搞砸了)并且在具体实现中删除它会使程序崩溃,因为它错了,亵渎神明并且不应该完成那里。

我该怎么办?

1 个答案:

答案 0 :(得分:2)

正如您所示,

IMovable不是一个抽象类,因为它没有自己的抽象方法。指向抽象类型的数据成员不计算在内。

在任何情况下,要回答你的问题,MovementPath需要一个虚拟析构函数,然后IMovable可以调用delete movementPath来调用正确的具体析构函数,无论它实际是什么类型

例如:

class MovementPath
{
...
public:
    virtual ~MovementPath() { ... }
...
};

class IMovable {
protected:
    MovementPath *movementPath;

public:
    IMovable() : movementPath(0) {}
    virtual ~IMovable() { delete movementPath; }

    void setMovementPath(MovementPath *newPath) {
        // whether or not you need to 'delete movementPath' here
        // depends on your particular requirements...
        movementPath = newPath;
    }
};

class MyMovementPath : public MovementPath
{
...
public:
    ~MyMovementPath() { ... }
...
};

class MyMovable : public IMovable
{
...
public:
    MyMovable() : IMovable() { ... }
    ~MyMovable() { ... }
...
};

MyMovementPath *path = new MyMovementPath;
MyMovable *movable = new MyMovable;
movable->setMovementPath(path);
...
delete movable; // <-- will delete the path as well...