如何将复制构造函数与动态分配一起使用

How to use copy constructor with dynamic allocation?

本文关键字:动态分配 一起 构造函数 复制      更新时间:2023-10-16

我在学校的一个练习中遇到了问题,我们需要对char数组和int数组使用动态分配。主要的是我不应该更改主函数和对象的构造方式。

class Automobile
{
 char* Name; //this is the name of the car that needs to be saved with dynamic alloc.
 int* Reg; //registration with dynamic alloc.
 int speed; //speed of the car
public:
Automobile(){ speed=0;}
Automobile(char* name,int* Reg,int speed)
{
    Name=new char[strlen(name)+1];
    strcpy(Name,name);
    Reg = new int[5];
    for(int i=0;i<5;i++)
    {
        this->Reg[i]=Reg[i];
    }
    this->speed=speed; //the normal constructor doesn't make any problems since it's called once
}
 Automobile(const Automobile& new)
 {
    Name= new char[strlen(new.Name)+1];
    strcpy(Name,new.Name);
    Reg=new int[5];
    for(int i=0; i<5; i++) Reg[i]=new.Reg[i];
    speed=new.speed;
}
 ~Automobile(){
    delete [] Name;
    delete [] Reg;
}
int main()
{
int n;
cin>>n;
for (int i=0;i<n;i++)
{
    char name[100];
    int reg[5];
    int speed;
    cin>>name;
    for (int i=0;i<5;i++)
        cin>>reg[i];
    cin>>speed;
    Automobile New=Automobile(name,reg,speed);
}

在主函数中,对象New被重新创建(??)循环,因此复制构造函数被调用(我对此不确定)。在复制构造函数中,我不删除内存(应该删除内存吗?),因此调试器向我显示,在我为名称创建新内存的行中存在问题。我尝试添加delete[]Name并将另一个对象的名称保存在临时指针中,这样我就可以将Name重新指定为临时对象,但这也不起作用。编译器在我构建它时没有显示任何错误,但我应该保存练习的页面显示我有bad_alloc(我不确定它是否连接到复制指针)。

在三参数构造函数中

Reg = new int[5];

分配给函数的参数,而不是成员
这会使成员未初始化(因为您没有初始化它),这会导致数组的复制在随机位置写入,这可能会失败,也可能不会失败
如果它没有失败,那么析构函数中的delete很可能会失败。

一个很好的解决方案是不将成员的名称重复用于同一范围内的其他对象(在这种情况下,重命名参数)
那么,忽略this->不仅不是灾难,甚至是建议。

您还忘记初始化默认构造函数中的指针成员。

附带说明:创建和初始化对象的规范方法是

Automobile New(name,reg,speed);