mardi 26 juin 2018

How to make the default destructor non-inline?

How can one force the compiler to make the default destructor of a class non-inline?

One way of doing this is to write an empty destructor definition, but it feels messy and also you get a warning from the static analyzer (clang-tidy in my case), that = default should be used for a trivial destructor.

To elaborate more on the actual use case - the goal is to have something similar to:

MyClass.h

class MyClassImpl;

class MyClass {
    std::unique_ptr<MyClassImpl> m_impl;
public:
    MyClass();
    // and some other methods
};

A std::unique_pointer to an incomplete type, which is forward declared in the header and the definition is known only in the source file.

The code above will give a compiler error:

error: use of undefined type 'MyClassImpl'

The actual problem is, that the default destructor of MyClass generated by the compiler is inline and so it needs the complete type info of MyClassImpl.

This can be fixed by adding an empty destructor for MyClass (by declaring in the header and defining in the source file, since defining in the header will implicitly make it inline which will cause the same error).

But is this the only way in modern C++?

Aucun commentaire:

Enregistrer un commentaire