Problem with virtual destructor when using templated operator delete
Asked Answered
U

1

10

The following class (with virtual destructor) contains a templated operator delete:

struct S
{
    virtual ~S() {}
    template <typename... Args>
    void operator delete(void* ptr, Args... args);
};

args can be empty, so I think S::operator delete can also be used when a usual delete is expected.

However (using g++), I get an error:

error: no suitable 'operator delete' for 'S'

Couldn't the "suitable 'operator delete'" be a template?

Ulane answered 11/8, 2022 at 14:34 Comment(1)
A template specialization is not what the standard calls a "usual deallocation function" (eel.is/c++draft/basic.stc.dynamic#deallocation-3.sentence-9), but these are the only once that are considered for delete expressions (eel.is/c++draft/expr.delete#9.sentence-3) and consequently also for virtual destructors.Ruder
G
15

Nope! For much the same reason that template<typename T> S(T const&) doesn't define a copy constructor. A lot of C++'s special member functions are required to not be templates. In this instance, a templated operator delete is only selected for use from a placement-new expression.

The reasoning is basically "better safe than sorry". If templates could bind in these special cases, it would be way too easy to accidentally declare a special member function you didn't want to. In the copy constructor case, note how declaring such a constructor -- just so you could bind to, say, any integer type -- would spookily inhibit move construction of the class if it counted as a copy constructor.

And if that's actually what you want, of course, you can just declare the non-placement-delete, or copy constructor, or what-have-you, and have it delegate to the template. So the design here offers safety without overly constraining you.

Guan answered 11/8, 2022 at 14:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.