C++26: Delete with a Reason -- Sandor Dargo

SANDOR_DARGO_ROUND.JPGLet’s start exploring C++26 with a simple but useful change. Thanks to Yihe Li’s proposal (2573R2), when we =delete a special member function or a function overload, we can specify a reason.

C++26: Delete with a Reason

by Sandor Dargo

From the article:

This is a practical and not very surprising change. Why do I say it’s not very surprising? Adding the ability to specify reasons for some operations has become a pattern in C++ evolution. Since C++11, we can add an optional message to static_assert, C++14 enriched the [[deprecated]] attribute with an optional reason, and the same happened in C++20 to the [[nodiscard]] attribute.

The reason is always similar, if not the same, to enhance maintainability and readability. When it comes to readability, not only the code but also the diagnostic messages become easier to grasp. Understanding why the compiler emitted a warning or an error becomes easier.

This latter is even more important than the readability of the codebase. I mean you could still add a comment right before or after a deleted function, but it wouldn’t be used in the compilers’ messages.

The usage is simple, if you want to specify a reason why a function or function overload is deleted, just pass a string literal containing the reason after delete surrounded by parentheses.

class NonCopyable
{
public:
    // ...
    NonCopyable() = default;

    // copy members
    NonCopyable(const NonCopyable&)
        = delete("Since this class manages unique resources, copy is not supported; use move instead.");
    NonCopyable& operator=(const NonCopyable&)
        = delete("Since this class manages unique resources, copy is not supported; use move instead.");
    
    // provide move members instead
    // ... 
};

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.