samedi 4 juin 2016

move semantic for vector in cpp

I am learning the move semantic in C++11, and I implement a simple class like this:

    class Big{
    public:
    int* data;

    Big() { cout << ">> create obj " << endl; 
        data = new int [100];
        for(int i=0; i<100; i++)
            data[i] = 0;
    }
    Big(const Big& other) { cout << ">> copy create obj " << endl; 
        data = new int [100];
        for(int i=0; i<100; i++)
            data[i] = other.data[i];
    }
    // try to use the move semantic in C++11
    Big(Big&& other) { cout << ">> move create obj " << endl; 
        data = other.data;
        other.data = NULL;
    }
    ~Big(){
        if(data){
            delete[] data;
            data = NULL;
        }
    }
};


int main(int argc, char const *argv[]){
    vector<Big> vb;
    // push the large objects to a vector
    for(int i=0; i<10; i++){
        Big b;
        vb.push_back(std::move(b));
    }
    return 0;
}

I compile the code with g++ test.cpp -std=c++11, run the code, and I get the answer like this:

>> create obj 
>> move create obj 
>> create obj 
>> move create obj 
>> copy create obj 
>> create obj 
>> move create obj 
>> copy create obj 
>> copy create obj 
>> create obj 
>> move create obj 
>> create obj 
>> move create obj 
>> copy create obj 
>> copy create obj 
>> copy create obj 
>> copy create obj 
......

Every time I call the vector.push_back function, the move constructor is called. But when the vector expands its size, it still uses the copy constructor.

I do not understand why std::vector call the copy constructor during expand, but not the move constructor? I think all the objects in the old vector become useless after the expand, so it will be a perfect chance to use the move constructor and move the objects to the new vector.

Is there any problem with my implementation of class Big? Or vector does not support move constructor during expand?

Aucun commentaire:

Enregistrer un commentaire