Disallowing class copying in C++

c++

Solution

In C++11 you can explicitly delete these functions (which is preferred over omitting the implementation, because it is more readable, and it will always generate a compiler-error, and not just a linker-error):

class MyClass
{
  char* _str;
  int _len;
  MyClass(const MyClass& rhs) = delete;
  MyClass& operator=(const MyClass& rhs) = delete;
public:
  MyClass();
  MyClass(const char *);
}

In C++03 you can use a base-class such as `boost::noncopyable` to achieve the same effect. This might be more readable (this is essentially the same approach as yours - this base-class has private copy-constructor and assignment-operator, so inheriting from it will make your class uncopyable):

class MyClass : boost::noncopyable
{
  char* _str;
  int _len;
public:
  MyClass();
  MyClass(const char *);
}

The difference between shallow and deep copying in C++ rests entirely in how you implement your copy-constructor (because your assignment operator should be implemented using your copy-constructor). If you don't have one, neither shallow nor deep copying is possible, if you have, it depends on how it is implemented.

Problem

When I want to disallow class copy in C++, I usually declare a private operator= and a copy constructor and I don't implement them: ``` class MyClass { char* _str; int _len; MyClass(const MyClass& rhs); //No implementation MyClass& operator=(const MyClass& rhs); //No implementation public: MyClass(); MyClass(const char *); } ``` Is this considered a bad style? Is there another way to do this?

Original source

Related problems