假设在 C++ 中我有一个接口(interface)类 Interface
,它只有纯虚函数。然后,其他类定义从该接口(interface)派生并为纯虚函数提供实现。
现在,有没有一种方法可以防止通过 Interface*
指针删除对象?我曾尝试删除构造函数,但派生类也无法销毁。
想法是传递对象指针,同时明确所有权不随指针传递这一事实。我知道还有其他方法可以实现这一点,我只是想知道它在 C++ 中是否可行。
最佳答案
您可以使析构函数 protected :
struct interface {
protected:
virtual ~interface(){}
};
struct concrete : interface {};
int main(){
//interface f; // error
//interface* f2 = new concrete();
//delete f2; // error
concrete c;
concrete* c2 = new concrete();
delete c2;
}
但是,请注意是 delete f2;
发出了错误,因此用户可能会受到诱惑 new interface
然后泄漏它。
另请注意,这在技术上是可行的,但不会解决任何问题。您总是需要知 Prop 体类型,否则您无法删除对象,这使得接口(interface)对于多态性基本上毫无用处。
关于c++ - 防止通过接口(interface)删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58976628/