0

There are some macros for preventing classes from being copied, eg: Macros to disallow class copy and assignment. Google -vs- Qt

Would I get identical results just by having a unique_ptr in my class? If so, is there a reason not to do this? eg

class Foo {
  private:
    std::unique_ptr<int> DISABLE_COPY;
};
Community
  • 1
  • 1
wrhall
  • 1,288
  • 1
  • 12
  • 26

2 Answers2

6

The disallow macros are really meant for C++98/03. C++11 has the = delete operator for eliminating copy/assignment. Adding a unique_ptr would bloat your class a little bit, but worse I think it's just a very roundabout and unclear way to implement deleted copy/assignment.

class Foo {
public:
  Foo(const Foo&) = delete;
  Foo& operator=(const Foo&) = delete;
};

Will achieve these results very clearly.

Sam Cristall
  • 4,328
  • 17
  • 29
  • So, the memory bloat shouldn't really matter since my class is presumably already large enough for me to disallow copy/assignment. I didn't realize the macros are not the best solution anymore, and most importantly -- I think the confusion of intent is the biggest problem. – wrhall Jun 05 '15 at 14:05
5

Yes, adding a unique_ptr<int> member would make your class noncopyable. But that's hardly the best solution. You just added 8 bytes to Foo, 8 bytes that didn't need to exist if you just did:

class Foo {
    Foo(const Foo&) = delete;
    Foo& operator=(const Foo&) = delete;
};

Furthermore, the compile errors when you try to copy accidentally will be much clearer. Consider the latest gcc:

main.cpp:17:13: error: use of deleted function 'Foo::Foo(const Foo&)'
     Foo g = f;
             ^
main.cpp:9:5: note: declared here
     Foo(const Foo&) = delete;
     ^

As opposed to:

main.cpp:17:13: error: use of deleted function 'Foo::Foo(const Foo&)'
 Foo g = f;
         ^
main.cpp:6:8: note: 'Foo::Foo(const Foo&)' is implicitly deleted because the default definition would be ill-formed:
 struct Foo {
        ^
main.cpp:6:8: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]'
In file included from /usr/local/include/c++/5.1.0/memory:81:0,
                 from main.cpp:4:
/usr/local/include/c++/5.1.0/bits/unique_ptr.h:356:7: note: declared here
       unique_ptr(const unique_ptr&) = delete;
       ^
Barry
  • 286,269
  • 29
  • 621
  • 977