Preventing Copying



Item 32. Preventing Copying

Access specifiers (public, protected, and private) can be used to express and enforce higher-level constraints on how a type may be used.

The most common of these techniques is to disallow copying of an object by declaring its copy operations to be private and not defining them:

class NoCopy {
  public:
    NoCopy( int );
    //...
  private:
    NoCopy( const NoCopy & ); // copy ctor
    NoCopy &operator =( const NoCopy & ); // copy assignment
};

It's necessary to declare the copy constructor and copy assignment operator, since otherwise the compiler would declare them implicitly, as public inline members. By declaring them to be private, we forestall the compiler's meddling and ensure that any use of the operationswhether explicit or implicitwill result in a compile-time error:

void aFunc( NoCopy );
void anotherFunc( const NoCopy & );
NoCopy a( 12 );
NoCopy b( a ); // error! copy ctor                            
NoCopy c = 12; // error! implicit copy ctor                   
a = b; // error! copy assignment                              
aFunc( a ); // error! pass by value with copy ctor            
aFunc( 12 ); // error! implicit copy ctor                     
anotherFunc( a ); // OK, pass by reference
anotherFunc( 12 ); // OK