开发者

assignment operator not always called

开发者 https://www.devze.com 2023-02-10 20:36 出处:网络
I have a template class with two functions, extracts shown below; template<class TYPE, class ARG_TYPE>

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号