Zack Lee
Zack Lee

Reputation: 3044

Is it good practice to write constructor/destructor?

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:
};

Upvotes: 8

Views: 1422

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283634

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.

Upvotes: 17

Related Questions