std :: array复制语义 [英] std::array copy semantics
问题描述
#include <array>
#include <iostream>
using namespace std;
struct SimpleDebugger
{
SimpleDebugger(int val = 0) : x(val) {
cout << "created" << endl;
}
SimpleDebugger(const SimpleDebugger &that) : x(that.x) {
cout << "copied" << endl;
}
~SimpleDebugger() {
cout << "killed!" << endl;
}
int getX() const {
return x;
}
void setX(int val) {
x = val;
}
private:
int x;
};
array<SimpleDebugger, 3> getInts(int i)
{
array<SimpleDebugger, 3> a;
a[0].setX(i);
a[1].setX(i + 1);
a[2].setX(i + 2);
cout << "closing getInts" << endl;
return a;
}
SimpleDebugger (*getIntsArray(int i)) [3] {
typedef SimpleDebugger SimpleDebugger3ElemArray [3];
SimpleDebugger3ElemArray *sd = new SimpleDebugger3ElemArray[1];
(*sd)[0].setX(i);
(*sd)[1].setX(i + 1);
(*sd)[2].setX(i + 2);
cout << "closing getIntsArray" << endl;
return sd;
}
ostream& operator << (ostream& os, const SimpleDebugger &sd) {
return (cout << sd.getX());
}
int main() {
auto x = getInts(5);
cout << "std::array = " << x[0] << x[1] << x[2] << endl;
auto y = getIntsArray(8);
cout << "Raw array = " << (*y)[0] << (*y)[1] << (*y)[2] << endl;
delete [] y;
}
输出
created
created
created
closing getInts
std::array = 567
created
created
created
closing getIntsArray
Raw array = 8910
killed!
killed!
killed!
killed!
killed!
killed!
我尝试了上述程序,以了解使用 std有多方便: :array
而不是原始数组,我知道避免使用老式数组是好的样式,甚至更好的方法是使用 std :: vector
。
I tried this above program to see how convenient it is to use std::array
over raw arrays, I know that avoiding old-style arrays is good style and even better is to use std::vector
.
我想知道在 std :: array
情况下,当函数 getInts()
返回。对于原始数组,我知道这是一个指针副本,清理起来的责任在于被调用者。在 std :: array
中不会发生这种情况,但是它如何在内部存储数据以及如何进行复制?
I'd like to know what happens under the hood in case of std::array
, when the function getInts()
returns. In case of the raw arrays, I know that it's a pointer copy and the onus of cleaning it up falls on the callee. In std::array
this doesn't happen, but how does it internally store the data and how does the copy happen?
推荐答案
std :: array
是一个聚合,其中包含数组作为其唯一的数据成员。复制或移动一个副本会将数组的每个元素复制或移动到新数组中。
std::array
is an aggregate, containing an array as its only data member. Copying or moving one will copy or move each element of the array into the new array.
在您的情况下,从函数返回副本时,该副本将被删除;在内部,该数组在 main
的自动存储中创建,函数填充该数组。
In your case the copy is being elided when it's returned from the function; under the hood, the array is created in automatic storage in main
, and the function fills in that array.
这篇关于std :: array复制语义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!