STD向量C++ - 深拷贝或浅拷贝
std vector C++ -- deep or shallow copy
我想知道复制一个向量我是否正在复制带有其值的向量(而这不适用于数组,深度复制需要一个循环或 memcpy)。
你能暗示一个解释吗?
问候
每当复制向量时,您都会进行深度复制。但是,如果你的向量是指针的向量,你得到的是指针的副本,而不是指向的值
例如:
std::vector<Foo> f;
std::vector<Foo> cp = f; //deep copy. All Foo copied
std::vector<Foo*> f;
std::vector<Foo*> cp = f; //deep copy (of pointers), or shallow copy (of objects).
//All pointers to Foo are copied, but not Foo themselves
Vector 将调整大小以有足够的空间容纳对象。然后,它将循环访问对象并为每个对象调用默认复制运算符。
这样,向量的副本是"深的"。矢量中每个对象的副本是为默认复制运算符定义的任何内容。
在示例中...这是错误的代码:
#include <iostream>
#include <vector>
using namespace std;
class my_array{
public:
int *array;
int size;
my_array(int size, int init_val):size(size){
array = new int[size];
for(int i=0; i<size; ++i)
array[i]=init_val;
}
~my_array(){
cout<<"Destructed "<<array[0]<<endl;
if(array != NULL)
delete []array;
array = NULL;
size = 0;
}
};
void add_to(vector<my_array> &container){
container.push_back(my_array(4,1));
}
int main(){
vector<my_array> c;
{
my_array a(5,0);
c.push_back(a);
}
add_to(c);
//At this point the destructor of c[0] and c[1] has been called.
//However vector still holds their 'remains'
cout<<c[0].size<<endl; //should be fine, as it copies over with the = operator
cout<<c[0].array[0]<<endl;//undefined behavior, the pointer will get copied, but the data is not valid
return 0;
}
这是更好的代码:
#include <iostream>
#include <vector>
using namespace std;
class my_array{
public:
int *array;
int size;
my_array(int size, int init_val):size(size){
cout<<"contsructed "<<init_val<<endl;
array = new int[size];
for(int i=0; i<size; ++i)
array[i]=init_val;
}
my_array(const my_array &to_copy){
cout<<"deep copied "<<to_copy.array[0]<<endl;
array = new int[to_copy.size];
size = to_copy.size;
for(int i=0; i<to_copy.size; i++)
array[i]=to_copy.array[i];
}
~my_array(){
cout<<"Destructed "<<array[0]<<endl;
if(array != NULL)
delete []array;
array = NULL;
size = 0;
}
};
void add_to(vector<my_array> &container){
container.push_back(my_array(4,1));
}
int main(){
vector<my_array> c;
{
my_array a(5,0);
c.push_back(a);
}
add_to(c);
//At this point the destructor of c[0] and c[1] has been called.
//However vector holds a deep copy'
cout<<c[0].size<<endl; //This is FINE
cout<<c[0].array[0]<<endl;//This is FINE
return 0;
}
相关文章:
- 与浅拷贝构造函数和深拷贝构造函数混淆
- 使用复制构造函数修复浅拷贝
- C++ 一个lambda浅拷贝const Type&如果它被赋予一个命名捕获,如[copy=val](){}?
- 在构造函数中浅拷贝字符串数组
- 如何将深拷贝构造函数实现到链表中?
- 为什么移动语义与动态 mem 分配中的浅拷贝具有相同的行为
- 在函数中传递带有指针成员的结构是浅拷贝或深拷贝在 C 中
- C++ 如何为地图创建浅拷贝构造函数
- 浅拷贝到协议缓冲区的字节字段中
- C++ 标准::字符串意外更改。我认为这个问题是关于深和浅拷贝的
- 如何正确制作抽象类的深拷贝?
- 为什么下面的类不对数组 arr 进行浅拷贝?
- 从功能返回时,向量的深拷贝行为
- 使用函子或lambda的矢量深拷贝
- STD向量C++ - 深拷贝或浅拷贝
- c++浅/深拷贝
- 懒惰复制-如何从浅拷贝创建深拷贝
- QVector::replace()创建深拷贝吗?
- multi_array_view没有深拷贝的作业
- 如何做深拷贝