如何将复制构造函数与动态分配一起使用
How to use copy constructor with dynamic allocation?
我在学校的一个练习中遇到了问题,我们需要对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);
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 在c++中使用动态分配的问题
- 使用递归模板动态分配的多维数组
- 对具有动态分配的内存和析构函数的类对象的引用
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 访问动态分配列表中的元素
- 为什么 std::equal_to会导致动态分配?
- 调用析构函数以释放动态分配的内存
- 动态分配Q_Property变量
- 在 C++ 中搜索动态分配的数组中的出现次数
- 动态分配的聊天数组打印缺失的数据和空
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 使用动态分配将 char* 复制到另一个字符**
- 使用指针在存在特征库的情况下动态分配 c++ 中的矩阵
- 二维阵列的动态分配
- 0xC0000005:访问冲突写入位置0xCDCDCDCD动态分配错误
- 我可以将 jsoncpp 与动态分配一起使用吗?
- 如何将复制构造函数与动态分配一起使用
- 将无序映射与动态分配的用户定义类一起使用