gpt4 book ai didi

c++ - 浅拷贝或深拷贝或数组

转载 作者:行者123 更新时间:2023-11-28 06:56:00 25 4
gpt4 key购买 nike

我正在尝试解决一个问题。我有一个带有 int 数组 prix 的类。如果我用复制构造函数复制对象 Test 。它会制作 int 数组 prix 的深拷贝还是浅拷贝?

我不能使用任何 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;
};

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

最佳答案

如果分配的数组的大小始终等于 1,那么构造函数将看起来像

Test(const Test & rhs) : id( rhs.id )
{
prix = new int[1];
*prix = *rhs.prix;
}

或者如果编译器支持初始化列表那么构造函数可以写成

Test(const Test & rhs) : id( rhs.id )
{
prix = new int[1] { *rhs.prix };
}

否则该类必须有一个额外的数据成员来包含数组中元素的数量。假设 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 );
}

例如你可以这样写

Test(const Test & rhs) : id( rhs.id ), size( rhs.size ), prix( new int[size] )
{
std::copy( rhs.prix, rhs.prix + rhs.size, prix );
}

但在这种情况下,数据成员大小必须在类定义中的数据成员 prix 之前定义。

关于c++ - 浅拷贝或深拷贝或数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23172128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com