Push Back with copy builder

Asked

Viewed 114 times

0

I don’t understand why when I create a copy constructor and push back on a vector, it calls the constructor more than once!

If I do only 1 push back, it will show 1 time the copy builder. if I do 2 push back increases to 3.

I would also like to know why I cannot use && in! foo(foo&& p){}

#include <iostream>
#include <vector>

using namespace std;

class foo {
public :

foo(const foo& p){

    cout<<"Construtor de Copia"<<endl;
    }

    foo () {
    cout << "Chamando o Construtor " << endl ;
    }

    ~ foo () {
    cout << "Chamando o Destrutor " << endl ;
    }
};

int main ( int argc , const char * argv []) {

    vector < foo > v3 ;

    foo f1;

    v3.push_back(f1);
    v3.push_back(f1);


    return 0;
}

1 answer

0


This happens because of the need to resize the size of std::vector due to push_back(), which results in extra copies. Reserving space a priori, this "problem" does not occur.

vector < foo > v3 ;
v3.reserve(2);

Upshot:

Chamando o Construtor 
Construtor de Copia
Construtor de Copia
Chamando o Destrutor 
Chamando o Destrutor 
Chamando o Destrutor

I would also like to know why I cannot use && in the constructor! foo(foo&& p){}

I’m not an expert on this, but as far as I know it’s possible, yes. In this case, you’d be declaring a motion constructor instead of a copy. This requires the use of std::move

v3.push_back(std::move(f1));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.