C++ class operation
-
The sample source code for question is as follows
class KcTest
{
public:
int m_nVal; // 0 or 1 for this sample
int *m_pVal; // Just for example, Don't say "Use array"!!KcTest(); KcTest( int v ); virtual ~KcTest(); KcTest operator=( const KcTest &b ); KcTest operator+( const KcTest &b );
};
KcTest::KcTest()
{
m_nVal = 0;
m_pVal = NULL;
}
KcTest::KcTest( int v )
{
m_nVal = 1;
m_pVal = new int(v);
}
KcTest::~KcTest()
{
m_nVal = 0;
if( m_pVal )
{
delete[] m_pVal;
m_pVal = NULL;
}
}
KcTest KcTest::operator=( const KcTest &b )
{
if( m_nVal != 1 || b.m_nVal != 1 || !m_pVal || !b.m_pVal )
{
KcTest ret;return ret; } for( int i=0; i
You can see code "a=b+c" in main() fn. I think the procedure for "a=b+c" is as follows; in operator+(), after calcunating c.m_pVal, creates new KcTest object and calls operator=() for new KcTest Obj. and deletes c-obj. so then it remains a = ( new KcTest Obj copied from operator+() ); But the real result of MS-Visual Studio is, in operator+() : calculating c.m_pVal -> deletes c-obj -> returns deleted c-obj So, a = ( deleted c-obj from operator+() ) <= error Is it right? My thought is wrong?