本文介绍了为什么enable_shared_from_this具有非虚拟析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个宠物项目,我在其中尝试了C ++ 11的新功能.虽然我有使用C的经验,但是我对C ++还是很陌生.为了使自己掌握最佳实践(除了大量阅读),我启用了一些严格的编译器参数(使用GCC 4.4.1):

I have a pet project with which I experiment with new features of C++11. While I have experience with C, I'm fairly new to C++. To train myself into best practices, (besides reading a lot), I have enabled some strict compiler parameters (using GCC 4.4.1):

-std=c++0x -Werror -Wall -Winline -Weffc++ -pedantic-errors

这对我来说很好.到目前为止,我已经能够解决所有障碍.但是,我需要enable_shared_from_this,这给我带来了问题.编译代码时(可能由-Weffc++触发),我得到以下警告(就我而言,是错误):

This has worked fine for me. Until now, I have been able to resolve all obstacles. However, I have a need for enable_shared_from_this, and this is causing me problems. I get the following warning (error, in my case) when compiling my code (probably triggered by -Weffc++):

base class ‘class std::enable_shared_from_this<Package>’ has a non-virtual destructor

因此,基本上,我对enable_shared_from_this的这种实现感到有些困惑,因为:

So basically, I'm a bit bugged by this implementation of enable_shared_from_this, because:

  • 用于子类化的意图的类的析构函数应该始终是虚拟的,恕我直言.
  • 析构函数为空,为什么要这么做?
  • 我无法想象有人会通过引用enable_shared_from_this来删除其实例.
  • A destructor of a class that is intended for subclassing should always be virtual, IMHO.
  • The destructor is empty, why have it at all?
  • I can't imagine anyone would want to delete their instance by reference to enable_shared_from_this.

但是我正在寻找解决这个问题的方法,所以我的问题是,是否有适当的方法来解决这个问题?并且:我以为这个析构函数是虚假的还是正确的呢?

But I'm looking for ways to deal with this, so my question is really, is there a proper way to deal with this? And: am I correct in thinking that this destructor is bogus, or is there a real purpose to it?

推荐答案

仅当要通过指向基类的指针删除派生类的实例时,才需要基类中的虚拟析构函数.

A virtual destructor in a base class is only needed if an instance of the derived class is going to be deleted via a pointer to the base class.

在类中具有任何虚拟函数(包括析构函数)都需要开销. Boost(以及TR1和C ++ 11标准库)不想因为您需要能够从this指针获得shared_ptr而强迫您承担这些开销.

Having any virtual function in a class, including a destructor, requires overhead. Boost (and the TR1 and C++11 Standard Library) doesn't want to force you to have that overhead just because you need to be able to obtain a shared_ptr from the this pointer.

如果您没有用户定义的构造函数,则编译器会为您提供一个构造函数,因此它并不重要.

If you don't have a user-defined constructor, the compiler provides one for you, so it doesn't really matter.

完全正确.

对于编译器警告,我将忽略该警告或将其抑制(在代码中以注释说明您这样做的原因).有时候,尤其是在学究"警告级别,编译器警告没有帮助,我会说这是其中一种情况.

As for the compiler warning, I would ignore the warning or suppress it (with a comment in the code explaining why you are doing so). Occasionally, especially at "pedantic" warning levels, compiler warnings are unhelpful, and I'd say this is one of those cases.

这篇关于为什么enable_shared_from_this具有非虚拟析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 17:38