tags:

views:

137

answers:

7

Is there a way by which we can prevent compilers from defining copy constructors, operator = overload for C++ classes.

+2  A: 

Defining? Well, yes. They are always declared (explicitly by you or implicitly by the compiler), but they are only defined by the compiler when/if you actually use them. Don't use them - and the compiler will not define them.

Of course, if by "prevent compilers from defining ...", you mean "prevent compilers from successfully defining...", i.e. if you want to make the implicit definition attempt fail at compile time, then you can achieve that by adding non-copy constructible and/or non-assignable subobject to your class (like a base or member with private copy-constructor and private assignment operator, for example).

AndreyT
@Matthieu M.: Firstly, what's "not necessarily"? `const` member is a non-assignable subobject. Secondly, what you are saying is not entirely correct. Copy-assignment is *always declared*. It is the *definition* attempt that will fail in case of a `const` member, just like I said in my answer.
AndreyT
+5  A: 

Yes. Derive from boost::noncopyable.

(There're also NIH ways to do that, by declaring the private never-defined methods for operator= and copy constructor, but, please love boost).

Pavel Radzivilovsky
+11  A: 

You can declare these functions as private which prevents people from using them when working with your class and at the same time prevents the compiler from generating them.

PeterK
+3  A: 

Declare those functions yourself and make them private. Also you can didn't write definitions of that functions, so everyone who try to use those functions - will get an linker error.

mOlind
+1  A: 

Inherit from a type that declares those functions in the private scope, such as boost::noncopyable.

Or...have a reference member variable :P

Noah Roberts
A: 

FWIW if you ever get around to using Qt then you can use the Q_DISABLE_COPY macro:

class Foo
{
public:
  Foo();

private:
  Q_DISABLE_COPY(Foo)
};
Rob
+3  A: 

In C++0x, you'll be able to write

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

Note that the compiler will not generate converting NonCopyable::operator=(Other const&) overloads in any case.

MSalters
You get much nicer error messages this way, at least in my opinion.
Dennis Zickefoose