如何使用动态分配的复制构造函数?

时间:2015-04-10 13:29:09

标签: c++ class copy-constructor dynamic-allocation bad-alloc

我在学校练习时遇到问题,我们需要为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);

}

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

1 个答案:

答案 0 :(得分:0)

这,在三参数构造函数

Reg = new int[5];

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

一个很好的解决方法是不在同一范围内重用其他内容的成员名称(在这种情况下重命名参数)。
然后遗漏this->不仅不是灾难,甚至是推荐。

您也忘了在默认构造函数中初始化指针成员。

旁注:创建和初始化对象的规范方法是

Automobile New(name,reg,speed);
相关问题