首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

拷贝构造函数中调用赋值函数解决办法

2012-09-20 
拷贝构造函数中调用赋值函数问题是这样的,我在拷贝构造函数中调用赋值函数,结果出现互相调用的情况,其他类

拷贝构造函数中调用赋值函数
问题是这样的,我在拷贝构造函数中调用赋值函数,结果出现互相调用的情况,其他类中也有类似的操作,但是没有出现问题,求解。
  struct SpecialSpeedLimit
  {
  unsigned int m_Value:16;
  unsigned int m_Direction:2;
  unsigned int m_Type:6;
  unsigned int m_Condition:8;
  unsigned int m_TimeZoneLen:16;
  unsigned int m_ValidityPeriodLen:16;
  unsigned char* m_pTimeZone;
  unsigned char* m_pValidityPeriod;

  SpecialSpeedLimit() : m_pTimeZone(NULL), m_pValidityPeriod(NULL)
  {
  clear();
  }

  ~SpecialSpeedLimit()
  {
  clear();
  }

  void clear()
  {
  m_Value = 0;
  m_Direction = 0;
  m_Type = 0;
  m_Condition = 0;
  m_TimeZoneLen = 0;
  m_ValidityPeriodLen = 0;

  if (m_pTimeZone != NULL)
  {
  delete[] m_pTimeZone;
  m_pTimeZone = NULL;
  }

  if (m_pValidityPeriod != NULL)
  {
  delete[] m_pValidityPeriod;
  m_pValidityPeriod = NULL;
  }
  }

  SpecialSpeedLimit(const SpecialSpeedLimit& rhs) : m_pTimeZone(NULL), m_pValidityPeriod(NULL)
  {
  this->operator=(rhs);
  }

  SpecialSpeedLimit operator=(const SpecialSpeedLimit& rhs)
  {
  if (this == &rhs) return *this;
  clear();
  m_Value = rhs.m_Value;
  m_Direction = rhs.m_Direction;
  m_Type = rhs.m_Type;
  m_Condition = rhs.m_Condition;

  if (rhs.m_pValidityPeriod!=NULL && rhs.m_ValidityPeriodLen>0)
  {
  m_ValidityPeriodLen = rhs.m_ValidityPeriodLen;
  m_pValidityPeriod = new unsigned char[rhs.m_ValidityPeriodLen];
  memcpy(m_pValidityPeriod, rhs.m_pValidityPeriod, rhs.m_ValidityPeriodLen);
  }

  if (rhs.m_pTimeZone!=NULL && rhs.m_TimeZoneLen>0)
  {
  m_TimeZoneLen = rhs.m_TimeZoneLen;
  m_pTimeZone = new unsigned char[rhs.m_TimeZoneLen];
  memcpy(m_pTimeZone, rhs.m_pTimeZone, rhs.m_TimeZoneLen);
  }  
  return *this;
  }
  };


当把这个类的对象push_back到一个vector的时候,个人觉得这个时候会调用拷贝构造函数,从而调用赋值函数,就结束了,但是我DEBUGDE 时候发现,当从赋值函数返回后到拷贝构造函数,这个时候又进到赋值函数了,如此下去,求解

[解决办法]
复制构造函数调用赋值函数不是好主意,因为在复制构造函数定义体内时,被构造对象还不存在呢(因为正在被构造),而调用赋值函数要求已经存在完整构造的对象,因此会导致未定义行为。

热点排行