Why does enable_shared_from_this have a non-virtual destructor?

后端 未结 3 1477
轻奢々
轻奢々 2021-02-07 04:21

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 re

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-07 04:46

    A destructor of a class that is intended for subclassing should always be virtual, IMHO.

    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.

    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.

    The destructor is empty, why have it at all?

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

    I can't imagine anyone would want to delete their instance by reference to enable_shared_from_this.

    Exactly.

    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.

提交回复
热议问题