Search code examples
c++c++11c-preprocessornoncopyabledeleted-functions

Macro to make class noncopyable


Is there any problem with following macro that makes a class non-copyable?

#define PREVENT_COPY(class_name) \
class_name(const class_name&) = delete;\
class_name& operator=(const class_name&) = delete;

class Foo
{
public:
    PREVENT_COPY(Foo)

    // .......
};

Solution

  • Typically, macros are generally constructed so they require a semi-colon at the end of the line, just like normal statements.

    Therefore, I suggest:

    #define PREVENT_COPY(class_name) class_name(const class_name&) = delete;\
                                     class_name& operator=(const class_name&) = delete
    

    Usage:

    class Foo
    {
    public:
        PREVENT_COPY(Foo); // Semi-colon required.
    
        // .......
    };