Reputation: 979
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?
I cannot use any stl containers ((
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?
Upvotes: 0
Views: 651
Reputation: 311068
If the allocated array always has size equal to 1 then the constructor will look as
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
#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.
Upvotes: 1