Preventing the compiler from defining copy constructors and operator = overload for C ++ classes

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

+6
c ++ class
source share
7 answers

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

+11
source share

Yes. Derive from boost :: noncopyable.

(There are also NIH ways to do this by declaring private, never-defined methods for the = operator and copy constructor, but please like the raise).

+6
source share

Declare these functions yourself and make them private. Also, you cannot write definitions of these functions, so anyone who tries to use these functions will receive a linker error.

+3
source share

In C ++ 0x you can write

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

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

+3
source share

Definition? Well yes. They are always declared (explicitly or implicitly by the compiler), but they are only defined by the compiler when / if you really use them. Do not use them - and the compiler will not detect them.

Of course, if you "forbid compilers to determine ..." means "prevent compilers from successfully determining ...", that is, if you want the implicit definition attempt to fail at compile time, you can achieve that by adding an unspecific constructive and / or an unassigned subobject to your class (for example, a base or a member with a private copy constructor and a private assignment operator, for example).

+2
source share

Inherit from a type declaring these functions in the private scope, for example boost :: noncopyable.

Or ... have a reference member variable: P

+1
source share

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

 class Foo { public: Foo(); private: Q_DISABLE_COPY(Foo) }; 
0
source share

All Articles