Creating a new object of class C with operator new() gives an error here:
class C
{
public:
C() {}
virtual ~C() {}
void operator delete(void*) = delete;
};
int main()
{
C* c = new C;
}
with C2280: 'void C::operator delete(void *)': function was explicitly deleted
But when I replace C() {}
with C() = default;
or remove the line so that compiler inserts a default constructor(which I believe has the same effect with = default
), the code will compile and run.
What are the differences between compiler-generated default constructor and user-defined default constructor that make this happen?
I got some hint in this posting, but class C here(without user-provided constructor) isn't trivial since the destructor is virtual, right?
Compiled with latest Visual Studio, c++17.
noexcept
– Vampirismoperator delete()
whether constructor is manually written or implicitly generated. Which is consistent with my expectations - since an exception may be thrown by thenew
expression, the compiler needs to accessoperator delete()
. – Dedalnoexcept
will make the code compile, but how...? – Townswomannoexcept
as SebastianRedl mentioned, then a call tooperator delete
needn't be included. Also g++ does only complain if the destructor is virtual. Otherwise it always compiles, even if the constructor is throwing. – Selfheal