c++ - Why does vector::push_back and emplace_back call value_type::constructor twice? -


i have class:

class foo { public:     foo() {}     foo(const foo&){cout << "constructed lvalue reference." <<endl; }     foo(foo&& ) {cout << "constructed rvalue reference." << endl; } }; 

then insert vector:

foo foo{}; vf.push_back(foo); 

the output surprising:

constructed lvalue reference. constructed lvalue reference. 

i assume got copied when passing parameters, tried:

vf.push_back(move(foo)); 

and

vf.push_back(forward<foo>(foo)); 

the output different due move semantics still calling constructor twice:

constructed rvalue reference. constructed lvalue reference. 

why constructors got called twice? how performance impact? how can avoid this?


i using mingw-gcc-4.7.1 on windows vista

total example:

#include <iostream> #include <vector>  using namespace std;  class foo { public:     foo() {}     foo(const foo&){cout << "constructed lvalue reference." <<endl; }     foo(foo&& ) {cout << "constructed rvalue reference." << endl; } };   int main(int argc, char **argv, char** envp) {     vector<foo> vf;     cout << "insert temporary." << endl;     vf.emplace_back(foo{});      foo foo{};     cout << "insert variable." << endl;     vf.emplace_back(foo);      return 0; } 

exact output:

insert temporary. constructed rvalue reference. insert variable. constructed lvalue reference. constructed lvalue reference. 

when insert new items in vector vector may have allocate more memory fit objects. when happens needs copy it's elements new memory location. invoke copy constructor. when insert element you're getting constructor new element , constructor when copying previous element.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -