是否可以从现有基类动态分配派生类所需的额外内存


是否可以

让派生类将额外的内存添加到从其他地方返回的指针?

原因是我正在使用一个返回Base *的库,并且我使用 Derived * 为其添加了一些额外的功能。问题是我必须在当前执行此操作时创建一个全新的对象,并且丢失了库内部用于更新的原始指针。

我尝试在简单代码中执行的操作的示例:

class Base 
{
public:
  Base() {}
  ~Base() = default;
  void BaseMethod();
private:
  int foo;
};
class Derived : public Base
{
public:
  Derived() : Base() {}
  ~Derived() = default;
  void DerivedMethod();
private:
  int bar;
}
// Somewhere else
Base* baseClass = new Base();
// This is the important part/question. 
// Is there some way to "allocate" the missing memory to make "baseClass" a Derived?
// I don't want to allocate an entirely new object, I just want to find out if it 
// is possible to allocate the missing memory to make Base a Derived 
// (and use the same pointer still)
Derived* derivedClass = SomehowAddExtraMemoryTo(baseClass);
不,

这是不可能的:本质上没有可用的 C 样式realloc可以以某种方式将Base*变成Derived*

但是我过去看到的一个"模式"涉及从Base继承存储指向Derived Base的指针:

class Derived : public Base
{
    Base* b;
};

然后,在 Derived 中编写一个方法来附加Base指针。这是您用来引入额外功能的技术。保留Base继承的事实意味着您可以在必要时将Derived*作为Base*传递。

当然,这有其危险性。您必须在所有方法中非常小心才能使用正确的指针b或基类this。另外,在销毁b时必须小心。如果可能的话,至少我会Derived不可复制的。

最新更新