Push Back with Copy Builder

0

I do not understand why when I create a copy constructor and push it back into a vector, it calls the constructor more than once!

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

I would also like to know why I can not use & in the builder! 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;
}
    
asked by anonymous 10.11.2016 / 17:36

1 answer

0

This is due to the need to resize the 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);

Result:

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 can not use & in the builder!    foo(foo&& p){}

I'm no expert on this, but as far as I know, it's possible. In case, you would be declaring a motion constructor instead of copy. To do this, you must use std::move

v3.push_back(std::move(f1));
    
10.11.2016 / 23:59