Click here to Skip to main content
15,896,207 members
Articles / Programming Languages / C++
Tip/Trick

Making Your Classes Copy-safe

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
11 Dec 2012CPOL 10.7K   3   3
Prevent default copy constructor and assignment operator side effect

I decided in the middle of my project to make my project follow coding standard, and be more secure and encapsulated.  For me, a small macro definition changed everything just by disabling coping for all objects and preventing generation of default copy constructor and assignment operator.

C++
#define DISABLE_COPY(CLASS_NAME) \
private: \  
CLASS_NAME ( const CLASS_NAME & );               // NOT IMPLEMENTED  \ 
CLASS_NAME & operator = ( const CLASS_NAME & );  // NOT IMPLEMENTED 

Inside your class, add this macro with the class name as parameter; just beside DECLARE_MESSAGE_MAP macro, for example.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Syrian Arab Republic Syrian Arab Republic
C++ , MFC , Win32 professional Developer.

Comments and Discussions

 
Questionprivate: Pin
alexander_st11-Dec-12 20:17
alexander_st11-Dec-12 20:17 
AnswerRe: private: Pin
Mr. Tines12-Dec-12 1:03
Mr. Tines12-Dec-12 1:03 
AnswerRe: private: Pin
Huzifa Terkawi12-Dec-12 2:46
Huzifa Terkawi12-Dec-12 2:46 
this is how you prevent access to them by making private , in general in design phase of your class you should decide whether your class should be copied or not , that way you tell other members of your team "This class is large use pass by reference or pointer" , to avoid side effect of dumb copy .
The boost idea sound right to me , but it need boost library !!
huzifa

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.