简体   繁体   English

赋值运算符并不总是被调用

[英]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. 这应该调用copy-constructor,而不是operator=() ,因为这不是赋值语句。 This is initialization. 这是初始化。

  • Initialization invokes copy-constructor. 初始化调用复制构造函数。 In initialization, a new object is constructed . 在初始化时,将构造一个新对象。
  • Assignment invokes operator=() . 赋值调用operator=() In assignment, old object is updated with a given value. 在分配中,旧对象将更新为给定值。

So, have you defined a copy-constructor for TYPE ? 因此,您是否为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. C ++标准规定了这种行为。 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. 将在构造对象上调用=时按您期望的方式调用赋值运算符-同样,将构造数组中的所有对象,这就是调用赋值运算符的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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