gpt4 book ai didi

c++ - 为什么类中的 C 样式数组没有用户定义的运算符 = 支持深度复制

转载 作者:太空宇宙 更新时间:2023-11-04 13:14:08 25 4
gpt4 key购买 nike

阅读std::array的源代码时

它是这样的:

template <typename T, int N>
struct array
{
T c_arr[N];
};

我想知道为什么在这种情况下自动生成的 operator= 支持深拷贝?

std::array<int, 3> a1{1, 2, 3}, a2;
a2 = a1;

//all the elements in a1.c_arr have been copied to a2.c_arr
copy(begin(a2), end(a2), ostream_iterator<int>(cout,"\t"));

output:
1 2 3

如果我们定义一个没有用户自定义operator=的类,它也支持深拷贝。

struct Test
{
int a[3];
};

Test a1{1, 2, 3}, a2;
a2 = a1;

//all the elements in a1.a have been copied to a2.a
copy(begin(a2), end(a2), ostream_iterator<int>(cout,"\t"));


output:
1 2 3

最佳答案

std::begin()std::end()std::array 的实例上返回开始和std::array 中实际数组的结束迭代器。

我不明白为什么复制构造函数与此有任何关系。我在这里没有看到任何地方发生复制构造。

关于c++ - 为什么类中的 C 样式数组没有用户定义的运算符 = 支持深度复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38277197/

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