简体   繁体   中英

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.

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 ?

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.

TYPE Element = newElement;

This is actually construction, not copy operator syntax. As such, it will invoke the copy constructor.

TYPE Element;
Element = newElement;

Will invoke the assignment operator as you expect as the = is invoked on the constructed object - likewise, all the objects in your array are constructed, which is why the assignment operator is invoked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM