使类不可复制的宏

时间:2015-02-27 16:52:57

标签: c++ c++11 c-preprocessor noncopyable deleted-functions

以下宏是否存在使类无法复制的问题?

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

class Foo
{
public:
    PREVENT_COPY(Foo)

    // .......
};

1 个答案:

答案 0 :(得分:1)

通常,宏的构造通常在行尾需要一个分号,就像普通语句一样。

因此,我建议:

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

用法:

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

    // .......
};