0

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)

    // .......
};
abelenky
  • 63,815
  • 23
  • 109
  • 159
quantum_well
  • 869
  • 1
  • 9
  • 17
  • 2
    You seem to be missing a continuation-slash on the first line of your macro. – abelenky Feb 27 '15 at 17:01
  • 2
    _"Is their any problem with following macro that makes class noncopyable?"_ Yes, it makes your code unreadable (less reliable) for anyone else. – πάντα ῥεῖ Feb 27 '15 at 17:02
  • @abelenky, moving an object isn't the same as copying it. Part of the point of *having* move constructors is to allow moving of things that can't be copied (such as `std::unique_ptr`). – Wyzard Feb 27 '15 at 17:11
  • 1
    @πάντα ῥεῖ I disagree, it's a lot more readable than a bunch of deleted functions/tors in the body of every class you don't want to copy. – BWG Feb 27 '15 at 17:14
  • I don't understand, placing the copy constructor and assignment *declarations* in the `private` section (without any implementation) should prevent copying. What's the need for the `= delete`? – Thomas Matthews Feb 27 '15 at 17:29
  • @ThomasMatthews: `private` is the "old way", and worked pretty good. But it still meant that objects could copy themselves. `= delete` is the new, C++11 way, and essentially forbids using that operation (which would otherwise be automatically generated). – abelenky Feb 27 '15 at 17:52

1 Answers1

2

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.

    // .......
};
abelenky
  • 63,815
  • 23
  • 109
  • 159