Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need for declare destructor as default

According to these guidelines:

If the default destructor is needed, but its generation has been suppressed (e.g., by defining a move constructor), use =default.

I can't imagine when code would be ill-formed without explicit default destructor in class which has move constructor.

Can somebody show me example confirms quote above?

struct S {
    S() {};
    S( S&& ) {}; // move ctor
};

int main() {
    S s; // there is no need to declare dtor explicitly =default
}
like image 427
αλεχολυτ Avatar asked Oct 21 '15 08:10

αλεχολυτ


People also ask

Do I need to declare a destructor?

No. You never need to explicitly call a destructor (except with placement new ). A class's destructor (whether or not you explicitly define one) automagically invokes the destructors for member objects. They are destroyed in the reverse order they appear within the declaration for the class.

What does the default destructor do?

The default destructor calls the destructors of the base class and members of the derived class. The destructors of base classes and members are called in the reverse order of the completion of their constructor: The destructor for a class object is called before destructors for members and bases are called.

Is it necessary to declare a destructor in a C++ program?

You only need to define a custom destructor when the class stores handles to system resources that need to be released, or pointers that own the memory they point to. In the preceding example, the destructor String::~String uses the delete operator to deallocate the space dynamically allocated for text storage.

What happens if destructor is not declared?

If destructor is not declared, compiler will generate destructor, that will call destructors of all members of object. Leak can be only if you are working with raw-memory (C files, memory allocation etc).


1 Answers

I think it would be some kind of mistake, the implicit declaration of default destructor should have nothing to do with the definition of a move constructor.

From the standard, 12.4$4,5 Destructors [class.dtor]

4 If a class has no user-declared destructor, a destructor is implicitly declared as defaulted (8.4). An implicitly-declared destructor is an inline public member of its class.

5 A defaulted destructor for a class X is defined as deleted if:

(5.1) — X is a union-like class that has a variant member with a non-trivial destructor,

(5.2) — any potentially constructed subobject has class type M (or array thereof) and M has a deleted destructor or a destructor that is inaccessible from the defaulted destructor,

(5.3) — or, for a virtual destructor, lookup of the non-array deallocation function results in an ambiguity or in a function that is deleted or inaccessible from the defaulted destructor.

like image 103
songyuanyao Avatar answered Oct 20 '22 21:10

songyuanyao