我刚刚在我的 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/