Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does the standard let me free-store allocate classes without destructors?

Tags:

c++

c++11

c++14

If you have a class without a destructor:

struct A {
    ~A() = delete;
};

The standard does not let me "locally" allocate an instance of that class:

int main()
{
    A a; //error
}

But it seems like it is ok if I allocate that on free-store:

int main()
{
    a *p = new A();
}

As long as I dont call delete on that pointer:

int main()
{
    a *p = new A();
    delete p; //error
}

So my question is, why does the standard let me have a class without a destructor if I allocate it on free-store? I would guess there are some use cases for that? But what exactly?

like image 208
Mac Avatar asked Apr 28 '16 23:04

Mac


People also ask

Do all classes need a destructor?

No. You never need to explicitly call a destructor (except with placement new ). A derived class's destructor (whether or not you explicitly define one) automagically invokes the destructors for base class subobjects. Base classes are destructed after member objects.

What if there is no destructor in C++?

If no user-defined destructor exists for a class and one is needed, the compiler implicitly declares a destructor. This implicitly declared destructor is an inline public member of its class.


1 Answers

So my question is, why does the standard let me have a class without a destructor if I allocate it on free-store?

Because that's not how standard features work.

The = delete syntax you're talking about was invented to solve a number of problems. One of them was very specific: making types that were move-only or immobile, for which the compiler would issue a compile-time error if you attempted to call a copy (or move) constructor/assignment operator.

But the syntax has other purposes when applied generally. By =deleteing a function, you can prevent people from calling specific overloads of a function, mainly to stop certain kinds of problematic implicit conversions. If you don't call a function with a specific type, you get a compile-time error for calling a deleted overload. Therefore, =delete is allowed to be applied to any function.

And the destructor of a class qualifies as "any function".

The designed intent of the feature was not to make types which would be non-destructible. That's simply an outgrowth of permitting =delete on any function. It's not design or intent; it simply is.

While there isn't much use to applying =delete to a destructor, there also isn't much use in having the specification to explicitly forbid its use on a destructor. And there certainly isn't much use in making =delete behave differently when applied to a destructor.

like image 153
Nicol Bolas Avatar answered Oct 15 '22 09:10

Nicol Bolas