std::数组复制语义
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
。
我想知道在std::array
的情况下,当函数getInts()
返回时,引擎盖下会发生什么。对于原始数组,我知道它是一个指针副本,清理它的责任落在被调用方身上。std::array
这不会发生,但它如何在内部存储数据以及如何进行复制?
std::array
是一个聚合,包含一个数组作为其唯一的数据成员。复制或移动一个会将数组的每个元素复制或移动到新数组中。
在您的情况下,当从函数返回副本时,副本将被省略;在后台,数组是在 main
的自动存储中创建的,并且函数填充该数组。
相关文章:
- 使用移动和复制语义时函数匹配如何工作?
- 移动语义和深层/浅层复制之间有什么关系?
- 了解构造函数在移动、复制、赋值语义中的行为
- 是否可以/希望创建不可复制的共享指针模拟(以启用weak_ptr跟踪/借用类型语义)?
- 复制省略并在返回值中移动语义
- 在一个微不足道的可复制结构中,移动语义应该实现吗?
- 在'string=string+s1'和"string+=s1"之间移动语义可以保存多少个复制操作?
- C++复制构造函数和移动语义之间的区别
- 默认情况下,返回是否使用移动或复制语义
- 我应该依赖复制省略还是移动语义
- 在封装指针的类中,移动语义无意中被复制构造函数取代
- 为什么 boost::make_shared 使用复制语义
- 复制有状态分配器:标准库分配器语义和内部内存
- 每次复制实现移动分配的非 const 对象时,我是否总是获得移动语义
- 如何使用C 11移动语义以明确避免复制
- 有没有一种非重复的方法允许程序员在成员初始化的复制和移动语义之间进行选择
- 从具有移动语义或返回值优化的函数返回值,但不返回复制构造函数
- 复制C++唯一指针的语义
- 链表复制/移动语义C++
- C++移动语义:为什么调用复制赋值运算符=(&)而不是移动赋值运算符=(&&)?