Is it good practice to write constructor/destructor?

Viewed 938

I wonder if it's a good practice to always write constructor/destructor even if I don't use them.

class Foo
{
public:
    Foo(){};
    ~Foo(){};
};

Or is it a better practice to write them only when I actually use them?

class Foo
{
public:
};
1 Answers

It's a bad idea to user-define special member functions when the default ones are sufficient.

  • You will lose the default-generated move operations, see Does a default virtual destructor prevent compiler-generated move operations?

  • Your class will no longer be trivial, causing allocation and deallocation and containers holding your class to become much less efficient.

  • The defaulted definitions may be automatically noexcept, but you lost that.

  • Your class is no longer an aggregate, so you can't use aggregate initialization.

  • If you make the destructor virtual, as shown in your question, you also lose standard-layout.

Related