Verify completeness of copy constructor

So after sometime I’m back with a new tip. You know I sometimes forget to adapt copy constructors when I add new members to a class. So at times I end up with strange bugs. So I’ve devised a small utility to remind me to update copy constructors after adding new members to class. Here is the utility…

[sourcecode language=”cpp”]#ifdef _DEBUG
#define VERIFY_COPY_CONSTRUCTOR(Class, OldSize)
if( sizeof( Class ) != OldSize )
{
TCHAR szBuf[512] = { 0 };
_stprintf_s(szBuf,
sizeof(szBuf)/sizeof(TCHAR),
_T( "Copy constructor not adapted for new membersnOld class size is: %dnNew class size is: %dn" ),
OldSize,
sizeof( Employee ));
::MessageBox( ::GetForegroundWindow(), szBuf, _T( "Error!" ), MB_OK|MB_ICONERROR );
__asm int 3
}
#else
#define VERIFY_COPY_CONSTRUCTOR(Class, Size)
#endif

class Employee
{
public:
Employee()
{
}

Employee( const Employee& Emp )
: m_Name( Emp.m_Name )
{
// Actual size as of now is 36.
VERIFY_COPY_CONSTRUCTOR( Employee, 32 );
}

private:
int m_Age;
std::string m_Name;
};[/sourcecode]

Note: 32 is given on purpose to trigger an assert.

Now when you run this code an error pops up which says that copy constructor is not updated. Last time when I updated Employee class copy constructor I only added copying code for m_Name but now I’ve got a new member and I forgot to update the copy constructor. So my utility jumps in and gives me this error dialog…


Error Dialog

Error Dialog

 

Note that new size of the class is given in the message box to help you update the hard coded size in the macro. The only thing that you should remember here is to update the hard coded size in the macro (well you’ll that’s for sure ;)).

PS: There is also something cooler which I didn’t try out yet. VC10 has something called static_assert which will be useful for such purposes. You can try out and let me know ;).

#ifdef _DEBUG
#define VERIFY_COPY_CONSTRUCTOR(Class, OldSize)
if( sizeof( Class ) != OldSize )
{
TCHAR szBuf[512] = { 0 };
_stprintf_s(szBuf, sizeof(szBuf)/sizeof(TCHAR), _T( “Copy constructor not adapted for new membersnOld class size is: %dnNew class size is: %dn” ), OldSize, sizeof( Employee ));
::MessageBox( ::GetForegroundWindow(), szBuf, _T( “Error!” ), MB_OK|MB_ICONERROR );
__asm int 3
}
#else
#define VERIFY_COPY_CLASS(Class, Size)
#endif

class Employee
{
public:
Employee()
{
}

Employee( const Employee& Emp )
{
VERIFY_COPY_CONSTRUCTOR( Employee, 35 );
}

private:
int m_Age;
std::string m_Name;
};

Appreciate your comments...