InsideDarkWeb.com

std::enable_shared_from_this, non-virtual destructor and public inheritance

The std::enable_shared_from_this class is a (template) mixin, recommended for use to enable creating shared pointers from a given object (or its address), which all have common ownership of the object.

The thing is, that if you have an class T which:

  1. Has virtual methods
  2. inherits from std::enable_shared_from_this<T> (and the inheritance must be public as detailed at the link above; otherwise the mixin is useless)
  3. Gets compiled with GCC with -Wnon-virtual-dtor (perhaps also with clang, I’m not sure)

you get warnings about the non-virtual destructor of std::enable_shared_from_this.

My question is – where is the fault here? That is…

  • Should std::enable_shared_from_this have a virtual destructor? (I don’t think so)
  • Should the non-virtual-destructor warning employ some criterion for when it is emitted (if at all enabled, that is)?
  • Should the destructor of std::enable_shared_from_this be made protected? (And will this even work?)
  • Should classes with this mixin not have virtual methods at all?

I’m confused.

Stack Overflow Asked on November 15, 2021

1 Answers

One Answer

There is no fault; your code is fine. It's merely a false-positive. The point of a warning is to detect pieces of code which, although valid C++, usually indicate problems. But "usually" does not mean "always", so most warnings have cases of false-positives, where it thinks there is misuse when there actually is not.

Should std::enable_shared_from_this have a virtual destructor?

No code is expected to delete a pointer to enable_shared_from_this. So no.

Should the non-virtual-destructor warning employ some criterion for when it is emitted (if at all enabled, that is)?

It's not reasonable for a compiler to know everything about what you're intending to do. It's just seeing something that's usually a problem, which you've decided to have it flag. In this case, it's not a problem.

Should the destructor of std::enable_shared_from_this be made protected?

No.

Should classes with this mixin not have virtual methods at all?

No.

Answered by Nicol Bolas on November 15, 2021

Add your own answers!

Related Questions

Replacement to getch based code block in cpp

1  Asked on July 24, 2020 by sonu-ishaq

         

Combining if let statements in Rust

1  Asked on July 24, 2020 by deniz-basgoren

 

Ask a Question

Get help from others!

© 2021 InsideDarkWeb.com. All rights reserved.