我想知道复制一个向量是否会将其值一并复制(而这在数组中不起作用,深度复制需要循环或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
int *a, *b; a=b; // 浅拷贝
。对于向量来说,我们也不是在做类似的事情吗?顺便说一下,它是 deep 而不是 deap :) - MaheshFoo
的复制构造函数或复制赋值函数的实现吗?它们中的一个最终被调用了吧?(如果是这种情况,是哪个?) - Gauthierstd::unique_ptr
还需要进行深拷贝吗? - Pr0metheanunique_ptr
的。对于 unique_ptr
,它不能被复制,你只能将其 move
或者创建一个新的并深度复制其内容。 - Andrew向量将调整大小以获得足够的空间,然后迭代遍历对象,并为每个对象调用默认的复制运算符。
这样,向量的复制是“深度”的。向量中每个对象的副本都是默认复制运算符定义的内容。
在示例中... 这是糟糕的代码:
#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;
}
vector
中使用memcpy
。vector
中包含的对象可能不是POD类型,它们可能是具有虚函数的类。请使用std::copy
或简单的vector<T>
到vector<T>
赋值。 - Ajay