浅或深复制或数组

时间:2021-01-12 04:22:13

I am trying to solve a problem. I have a class with an int array prix. If I copy the object Test with the copy constructor. Will it make a deep or a shallow copy of the int array prix?

我正在努力解决问题。我有一个带有int数组prix的类。如果我使用复制构造函数复制对象Test。它会制作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?

编辑:那时我错了,它只是一个指针。如何复制指向的数组?

1 个解决方案

#1


1  

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. Then the constructor will look as

否则,类必须有一个额外的数据成员,该成员将包含数组中的元素数。假设size_t size是这样的数据成员。然后构造函数看起来像

#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之前定义数据成员大小。

#1


1  

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. Then the constructor will look as

否则,类必须有一个额外的数据成员,该成员将包含数组中的元素数。假设size_t size是这样的数据成员。然后构造函数看起来像

#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之前定义数据成员大小。