Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assignment operator not always called

I have a template class with two functions, extracts shown below;

template<class TYPE, class ARG_TYPE>
int MyClassT<TYPE, ARG_TYPE>::Add(ARG_TYPE newElement)
{ 
    TYPE Element = newElement; <--- TYPE operator= not called, shallow copy
'
'
}

and

template<class TYPE, class ARG_TYPE>
void MyClassT<TYPE, ARG_TYPE>::SetAt(int nIndex, ARG_TYPE newElement)
{ 
,
,
m_pData[nIndex] = newElement;  <--- TYPE operator= is called, deep copy

'
'
}

Why does the first case result in a shallow copy, yet the second case in a deep copy? I'm assuming a copy constructor is being substituted in the first case, but don't see why.

like image 361
SmacL Avatar asked Jul 10 '26 13:07

SmacL


2 Answers

TYPE Element = newElement; <--- TYPE operator= not called, shallow copy

This should call copy-constructor, not operator=(), as this is not assignment statement. This is initialization.

  • Initialization invokes copy-constructor. In initialization, a new object is constructed.
  • Assignment invokes operator=(). In assignment, old object is updated with a given value.

So, have you defined a copy-constructor for TYPE?

like image 177
Nawaz Avatar answered Jul 12 '26 03:07

Nawaz


I'm assuming a copy constructor is being substituted in the first case, but don't see why.

That is exactly what is happening. The C++ standard mandates this behaviour. You should make your copy constructor do the same thing as your assignment operator.

like image 36
Martin Stone Avatar answered Jul 12 '26 04:07

Martin Stone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!