A Developer's Diary

Jul 19, 2010

C++ Idioms - Non Copyable Objects

The Non Copyable idiom in C++ allows us to create classes whose objects cannot be constructed using a copy constructor or assigned to another. Some of the classes using this idiom provide mutually exclusive access to the resources e.g. Mutex, Semaphores, Document, Memory, File etc

Key Idea
To prevent objects of a class from being copy constructed or assigned to each other, declare the copy constructor and the assignment operator as private and do not provide implementations
//File: NonCopyable.h
#include <iostream>

class NonCopyable
{
protected:
    NonCopyable(){}
    ~NonCopyable(){}

private:
    //Restrict the copy constructor
    NonCopyable(const NonCopyable&);
    //Restrict the assignment operator
    NonCopyable& operator=(const NonCopyable&);
};

CantCopy - a non copyable class example
//File: CantCopy.h
#include <iostream>
#include <string>
#include "NonCopyable.h"

using namespace std;

class CantCopy : private NonCopyable
{
public:
    CantCopy(const std::string& str);
    ~CantCopy();

    const char* getClassName();

private:
    CantCopy();
    std::string name;
};

//File: CantCopy.cpp
#include "CantCopy.h"

CantCopy::CantCopy(const std::string& str)
{
    name = str;
}

CantCopy::~CantCopy()
{
}

const char* CantCopy::getClassName()
{
    return name.c_str();
}

//File: Main.cpp
#include "CantCopy.h"

int copy(CantCopy obj) // a copy is passed as parameter
{
    return 0;
}

int main()
{
    CantCopy cc("Mike"), cc1("Perry");

    //CantCopy cc2(cc);  //Error: 'NonCopyable::NonCopyable' : cannot access private member declared in class 'NonCopyable'
    //CantCopy cc3 = cc; //Error: 'NonCopyable::NonCopyable' : cannot access private member declared in class 'NonCopyable'
    //cc1 = cc;          //Error: 'NonCopyable::operator =' : cannot access private member declared in class 'NonCopyable'
    //copy(cc);          //Error: 'NonCopyable::NonCopyable' : cannot access private member declared in class 'NonCopyable'

    return 0;
}

No comments :

Post a Comment