std vector C++ — deep or shallow copy

后端 未结 2 2085
礼貌的吻别
礼貌的吻别 2020-12-24 05:09

I wonder whether copying a vector I am copying the vector with its values (whereas this is not working with array, and deep copy need a loop or memcpy).

Could you hi

2条回答
  •  抹茶落季
    2020-12-24 05:29

    Vector will resize to have enough space for the objects. It will then iterate through the objects and call the default copy operator for every object.

    In this way, the copy of the vector is 'deep'. The copy of each object in the vector is whatever is defined for the default copy operator.

    In examples... this is BAD code:

    #include 
    #include 
    
    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 &container){
        container.push_back(my_array(4,1));
    }
    
    int main(){
    
        vector 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<

    This is BETTER code:

    #include 
    #include 
    
    using namespace std;
    
    class my_array{
    public:
        int *array;
        int size;
        my_array(int size, int init_val):size(size){
            cout<<"contsructed "< &container){
        container.push_back(my_array(4,1));
    }
    
    int main(){
    
        vector 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<

提交回复
热议问题