Skip to content

Instantly share code, notes, and snippets.

@is
Created August 9, 2018 15:56
Show Gist options
  • Save is/50c502371326fc6eb3e8b9741a89e351 to your computer and use it in GitHub Desktop.
Save is/50c502371326fc6eb3e8b9741a89e351 to your computer and use it in GitHub Desktop.
vector::push_back vs vector::emplace_back
Constructor 0x7fffad4b75d0:A0,0
--1--
Copy constructor 0x55b854a6ee70:A0,0
16
--2--
Constructor 0x7fffad4b7600:push,10
Copy constructor 0x55b854a6ee98:push,10
Destructor 0x7fffad4b7600:push,10
16
--3--
Constructor 0x55b854a6eec0:emplace_0,20
16
--4--
Constructor 0x7fffad4b7600:emplace_1,30
Copy constructor 0x55b854a6eee8:emplace_1,30
Destructor 0x7fffad4b7600:emplace_1,30
16
--5--
Copy constructor 0x55b854a6ef10:A0,0
16
--end--
5
Destructor 0x7fffad4b75d0:A0,0
Destructor 0x55b854a6ee70:A0,0
Destructor 0x55b854a6ee98:push,10
Destructor 0x55b854a6eec0:emplace_0,20
Destructor 0x55b854a6eee8:emplace_1,30
Destructor 0x55b854a6ef10:A0,0
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class A {
public:
A(string a, int b):a_(a), b_(b) {
cout << "Constructor " <<(void*)this <<":" << a_ << "," << b_ << endl;
}
A(const A& a):a_(a.a_), b_(a.b_) {
cout << "Copy constructor " << (void*)this << ":" << a_ << "," << b_ << endl;
}
~A() {
cout << "Destructor " << (void*)this << ":" << a_ << "," << b_ << endl;
}
private:
string a_;
int b_;
};
int main()
{
vector<A> as;
as.reserve(16);
// as.reserve(16);
A a0("A0", 0);
cout << "--1--" << endl;
as.push_back(a0);
cout << as.capacity() << endl;
cout << "--2--" << endl;
as.push_back(A("push", 10));
cout << as.capacity() << endl;
cout << "--3--" << endl;
as.emplace_back("emplace_0", 20);
cout << as.capacity() << endl;
cout << "--4--" << endl;
as.emplace_back(A("emplace_1", 30));
cout << as.capacity() << endl;
cout << "--5--" << endl;
as.emplace_back(a0);
cout << as.capacity() << endl;
cout << "--end--" << endl;
cout << as.size() << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment