If I don't want my object copyable...

All I have to do is declare the overloaded assignment operator, and copy constructor, as private, correct? There are NO other ways in which my object could be copied?

I have a class that is implemented with pointers and because default copy constructor and assignment operator use memberwise(shallow) copying, I don't want copying enabled at the moment until I feel like implementing the functionality :o)
All I have to do is declare the overloaded assignment operator, and copy constructor, as private, correct?

Pretty much. In the olden days you declared them as private and did not provide an implementation.

But if you are using a C++11 compliant compiler you could delete them instead. (You also have to worry about movability as well as copyability.)

1
2
3
4
5
6
class MyClass
{
public:
    MyClass(const MyClass&) = delete;
    MyClass& operator=(const MyClass&) = delete;
};


With explicitly deleted member functions in C++11, is it still worthwhile to inherit from a noncopyable base class?
http://stackoverflow.com/questions/9458741/with-explicitly-deleted-member-functions-in-c11-is-it-still-worthwhile-to-inh

For pre-C++11 code you could consider using (or taking inspiration from) Boost noncopyable
http://www.boost.org/doc/libs/1_55_0/boost/noncopyable.hpp

Andy
Last edited on
By default, a class has 5 operations:

copy assignment
copy constructor
move assignment
move constructor
destructor

If you declare any of those you must consider all and explicitly define or default the ones you want. Think of copying, moving, and destruction as closely related operations, rather than individual operations that you can freely mix and match - you can specify arbitrary combinations, but only a few combinations make sense semantically.
If any move, copy, or destructor is explicitly specified (declared, defined, =default, or =delete) by the user, no move is generated by default. If any move, copy, or destructor is explicitly specified (declared, defined, =default, or =delete) by the user, any undeclared copy operations are generated by default, but this is deprecated, so don't rely on that.
...
I strongly recommend that if you declare one of these five function, you explicitly declare all.
- Stroustrup http://www.stroustrup.com/C++11FAQ.html#default2
Topic archived. No new replies allowed.