fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. class Foo {
  7.  
  8. public:
  9. Foo() {}
  10. virtual ~Foo() {}
  11. Foo(const Foo&){cout << "constructed by lvalue reference." <<endl; }
  12. Foo(Foo&){cout << "constructed by non-const lvalue reference." <<endl; }
  13. Foo(Foo&& ) noexcept {cout << "constructed by rvalue reference." << endl; }
  14. };
  15.  
  16.  
  17. int main(int argc, char **argv, char** envp)
  18. {
  19. vector<Foo> vf;
  20. cout << "Insert a temporary. One move:" << endl;
  21. vf.emplace_back(Foo{});
  22. cout << "Insert a temporary(2). Two moves:" << endl;
  23. vf.emplace_back(Foo{});
  24. cout << "Resize with temporary(3). Two moves:" << endl;
  25. vf.resize(10);
  26.  
  27. vector<Foo> vf2;
  28. Foo foo{};
  29. cout << "Insert a variable. One copy:" << endl;
  30. vf2.emplace_back(foo);
  31. cout << "Insert a variable(2). One move, one copy:" << endl;
  32. vf2.emplace_back(foo);
  33. cout << "Resize with variable(3). Two moves:" << endl;
  34. vf2.resize(10);
  35.  
  36. vector<Foo> vf3;
  37. cout << "Insert a nothing. No copy or move:" << endl;
  38. vf3.emplace_back();
  39. cout << "Insert a nothing(2). One move:" << endl;
  40. vf3.emplace_back();
  41. cout << "Resize with nothing(3). Two moves:" << endl;
  42. vf3.resize(10);
  43. }
  44.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
Insert a temporary.  One move:
constructed by rvalue reference.
Insert a temporary(2).  Two moves:
constructed by rvalue reference.
constructed by rvalue reference.
Resize with temporary(3).  Two moves:
constructed by rvalue reference.
constructed by rvalue reference.
Insert a variable.  One copy:
constructed by non-const lvalue reference.
Insert a variable(2).  One move, one copy:
constructed by non-const lvalue reference.
constructed by rvalue reference.
Resize with variable(3).  Two moves:
constructed by rvalue reference.
constructed by rvalue reference.
Insert a nothing.  No copy or move:
Insert a nothing(2).  One move:
constructed by rvalue reference.
Resize with nothing(3).  Two moves:
constructed by rvalue reference.
constructed by rvalue reference.