我有叫做“Base”和“Derived”的类。
现在让我们介绍另外两个类,它们分别被称为
struct Base {
Base() = default;
virtual ~Base() = default;
Base(const Base&) = delete;
Base& operator=(const Base&) = delete;
virtual void DoStuff() = 0;
};
“Base”类需要虚析构函数,这是可以理解的。此外,我不允许复制这个类。
struct Derived : Base {
Derived() = default;
~Derived() override = default;
void DoStuff() override { /*...*/ }
};
int main()
{
std::shared_ptr<Base> a = std::make_shared<Derived>();
a->DoStuff();
return 0;
}
现在让我们介绍另外两个类,它们分别被称为
Callable
和DerivedCallable
。struct Callable
{
virtual void Call() = 0;
};
struct DerivedCallable : Base, Callable
{
DerivedCallable() = default;
~DerivedCallable() override = default;
void DoStuff() override { /*...*/ }
void Call() override { /*...*/ }
};
int main()
{
std::shared_ptr<Base> a = std::make_shared<Derived>();
a->DoStuff();
{
auto callableA = std::dynamic_pointer_cast<DerivedCallable>(a);
if(callableA) {
callableA->Call();
}
}
std::shared_ptr<Base> b = std::make_shared<DerivedCallable>();
b->DoStuff();
{
auto callableB = std::dynamic_pointer_cast<DerivedCallable>(b);
if(callableB) {
callableB->Call();
}
}
return 0;
}
Derived
没有继承 Callable
,所以 callableA
是 nullptr,因此 if 语句不会执行 Call()
函数。
另一方面,DerivedCallable
继承自 Callable
,而 std::dynamic_pointer_cast
将增加对象的引用计数到 2,因此当 callableB
超出作用域时,对象不会被释放,只有引用计数会减少到 1,然后主函数将释放 b
。
Callable
需要有虚析构函数吗?
operator=
和~Derived() override = default
。 - Edziju