如何在另一个结构中使用结构对象和结构

how to use object of structure with constructure in another structure?

本文关键字:结构 对象 另一个      更新时间:2023-10-16

我有一个结构,它有两个构造函数,其中有一个byte*成员,如下所示:

struct structA
{
   byte* pData;  int nLength;
  structA()
  {
    pData = NULL; nLength = 0;
  }
  structA(int nLen)
  {
    pData = new byte[nLen];  nLength = nLen;
  }
  ~structA()
  {
    delete[] pData;
  }
}

另一个结构,即structB,有一个structA:列表

struct structB
{
  CList <structA, structA&> AList;
}

现在,我创建了一个structA的对象,参数10作为输入,并将其添加到structB:的对象中

//范围的开始

structA osA(10);
structB osB;
osB.AList.AddTail(osA);

//范围结束

问题是,当程序退出作用域时,structA的析构函数被调用2次,程序崩溃。

问题是什么,为什么会发生?任何帮助都与相关

您需要一个复制构造函数(或移动构造函数)。编译器默认的复制构造函数将只复制指针,然后当您退出时,两个对象都将删除同一指针。