[英]shallow or deep copy or the array
I am trying to solve a problem. 我正在尝试解决问题。 I have a class with an int array prix. 我有一个带有int数组prix的类。 If I copy the object Test with the copy constructor. 如果我使用复制构造函数复制对象Test。 Will it make a deep or a shallow copy of the int array prix? 它会复制int数组prix的深层副本还是浅层副本?
I cannot use any stl containers (( 我不能使用任何Stl容器((
Test
{
Test(const char *id), id(id);
{
prix=new int[1];
}
Test(const Test & rhs):
id(rhs.id),
prix(rhs.prix)
{}
//...
const char *id;
int * prix;
};
edit: I was wrong then, it is just a pointer. 编辑:那时候我错了,那只是一个指针。 How can I copy the array which is pointed? 如何复制指向的数组?
If the allocated array always has size equal to 1 then the constructor will look as 如果分配的数组的大小始终等于1,则构造函数将看起来像
Test(const Test & rhs) : id( rhs.id )
{
prix = new int[1];
*prix = *rhs.prix;
}
Or if the compiler supports initializer lists then the constructor can be written as 或者,如果编译器支持初始化程序列表,则构造函数可以写为
Test(const Test & rhs) : id( rhs.id )
{
prix = new int[1] { *rhs.prix };
}
Otherwise the class has to have an additional data member that will contain the number of elements in the array. 否则,该类必须具有一个额外的数据成员,该成员将包含数组中的元素数量。 Let assume that size_t size
is such a data member. 假设size_t size
是这样的数据成员。 Then the constructor will look as 然后构造函数将看起来像
#include <algorithm>
//...
Test(const Test & rhs) : id( rhs.id ), size( rhs.size )
{
prix = new int[size];
std::copy( rhs.prix, rhs.prix + rhs.size, prix );
}
You could write for example as 你可以写例如
Test(const Test & rhs) : id( rhs.id ), size( rhs.size ), prix( new int[size] )
{
std::copy( rhs.prix, rhs.prix + rhs.size, prix );
}
but in this case data member size has to be defined before data member prix in the class definition. 但是在这种情况下,必须在类定义中的数据成员prix之前定义数据成员的大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.