c++ - 接口(interface)和-Wctor-dtor-privacy

标签 c++

我刚刚在我的 makefile 中添加了选项 Wctor-dtor-privacy-Wnon-virtual-dtor 并且在我的一个文件中出现错误提示。我通常为我的基类编写私有(private)非虚拟析构函数或公共(public)虚拟析构函数。但是我收到了一个关于我的一个类的警告,它是一个接口(interface):

class TestInterface
{
public:
    virtual void Send( const std::string& sendMessage ) = 0;
    virtual std::string PopMessage() = 0;
    virtual std::string GetLatestString() = 0;
    virtual std::string::size_type GetReceivedBufferSize() const = 0;
};

warning: all member functions in class ‘TestInterface’ are private [-Wctor-dtor-privacy]
warning: ‘TestInterface’ has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]

我理解这个警告,并且我倾向于为我的所有接口(interface)编写一个公共(public)虚拟析构函数,这很好。但我不明白为什么很多网站(一些教授 CPP)不理会这个 e.g. .如果类使用不当,可能会导致一些错误,对吗?

最佳答案

通过将方法声明为虚拟的,您表明这些方法将被某些子类覆盖。如果您不提供虚拟析构函数,通过指针删除子类将导致未定义行为。见

When to use virtual destructors? .

http://www.parashift.com/c++-faq/virtual-dtors.html

这可能是由于过于关注特定方面或避免导致未定义行为的用法而被省略。

关于c++ - 接口(interface)和-Wctor-dtor-privacy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20546487/

相关文章:

c++ - 无对象连接

c++ - Makefile 改进,依赖生成不起作用

c++ - 防止被零除的适当行为

c++ - 从 "float"到 "int"的缩小转换无效

c++ - 如何通过q​​pOASES的SymSparseMat类创建对称稀疏矩阵?

c++ - 最小化和最大化窗口的事件处理程序

c++ - RInside 编译 : Make Targets

c++ - 如何从该指针获取指针指向的值的地址

C++ 解释赋值中的大括号?

c++ - C++中动态数组的通用类