Once More About the Rule of 5 -- Sandor Dargo

SANDOR_DARGO_ROUND.JPGIn a recent talk at C++OnSea, Arne Mertz highlighted common misuses of guidelines, including the Rule of Five. This discussion prompted me to reflect on a recurring pattern I've observed in C++ classes that explicitly default constructors and destructors, leading to unexpected behaviors with move semantics.

Once More About the Rule of 5

by Sandor Dargo

From the article:

Let’s first repeat what the rule of 5 says.

The Rule of Five tells us that if we need to define any of a copy constructor, copy assignment operator, move constructor, move assignment operator or destructor then we usually need to define all five.

Fair enough.

Have you ever seen classes where the default constructor and destructor are explicitly defaulted? Like this?

class SomeClass {
public:
    SomeClass() = default;
    ~SomeClass() = default;

    void foo();
private:
    int m_num{42};
};

First of all, that’s not the best idea. You can simply remove them. But let’s assume that you cannot remove the user-provided destructor for some reason. Maybe it’s not defaulted and it does something.

What does the famous Hinnant table tell us?

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.