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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.