Jump to content
  • Advertisement
Sign in to follow this  
  • entries
  • comments
  • views

NonCopyable objects

Sign in to follow this  


Sometimes, you don't want to encounter a situation where something made a copy of the object. In C++, a copy of an object can be made in a number of situations. The most obvious is direct assignment. Less obvious, but equally valid, is a function call using pass-by-value.

Copying in C++ is handled in two ways

  • the copy assignment operator; and
  • the copy constructor

    Unfortunately, if the class definition does not explicitly declare a copy constructor or a a copy assignment operator, the compiler provides an implicit version which is a public member function.
    Now, if we want to make a class noncopyable, we can simply define its copy constructor and copy assignment operator as private members. But, it makes more sense to have a noncopyable base class. If a class derives from the noncopyable base class, it too will be noncopyable, since the copy of an object of a derived class must necessarily invoke the copy constructor or copy assignment operator of the corresponding base class.
    namespace Base
    class cNonCopyable
    cNonCopyable(const cNonCopyable&);
    cNonCopyable operator =(const cNonCopyable&);

    By making the copy constructor or copy assignment operator private, we ensure that the derived class is noncoyable as well. By just providing the declaration and not implementing them, we ensure that the compiler does not provide its own versions and a linking error is generated if they are used anywhere in the program.
Sign in to follow this  


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!