gpt4 book ai didi

c++ - C++ 核心指南 C35 "A base class destructor should be either public and virtual, or protected and nonvirtual"对于接口(interface)类是否错误?

转载 作者:行者123 更新时间:2023-12-02 02:28:56 24 4
gpt4 key购买 nike

假设我有以下接口(interface)类,以便“写入接口(interface),而不是实现”:

class IDrawable
{
public:

virtual void
Draw() const = 0;

protected:

~IDrawable() = default;
};

客户端不应该能够通过接口(interface)指针删除动态分配的可绘制对象,因此 IDrawable 的析构函数被设置为 protected 且非虚拟的,如 C++ Core guideline C.35: A base class destructor should be either public and virtual, or protected and nonvirtual.

现在对于实现此接口(interface)的类:

class CDrawable : public IDrawable
{
public:

void
Draw() const override;
};

这当然会发出警告:

CDrawable has virtual functions but non-virtual destructor.

为了解决这个问题,我们现在必须向 CDrawable 添加一个虚拟析构函数。但在派生类中拥有虚拟析构函数感觉像是一种代码味道,我之前没有见过(?)在 IDrawable 中拥有虚拟 protected 析构函数不是更有意义吗?与指南所说的相反?

最佳答案

技术上没有问题。您的 CDrawable 有一个公共(public)非虚拟析构函数(隐式定义)。调用它不会导致未定义的行为,除非它是在从 CDrawable 派生的类上调用的。如果您只有对 IDrawable 的引用并调用其析构函数,您将跳过派生类的销毁(我认为导致 UB),但由于它不可公开访问,所以这不是问题。

是的,您会收到警告。然而,该警告只是表明某些地方可能出现问题。在本例中,事实并非如此。

关于c++ - C++ 核心指南 C35 "A base class destructor should be either public and virtual, or protected and nonvirtual"对于接口(interface)类是否错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60362058/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com