Skip to content

Instantly share code, notes, and snippets.

@junfenglx
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junfenglx/df439cb9c5ecd9b3b6f8 to your computer and use it in GitHub Desktop.
Save junfenglx/df439cb9c5ecd9b3b6f8 to your computer and use it in GitHub Desktop.
use push_back demonstrates
#include <iostream>
#include <ostream>
#include <string>
#include <vector>
//comment this define to see reallocate
#define F4
class Test {
public:
std::string tag;
Test(std::string &t) : tag(t) {
std::cout << "Constructed" << '\n';
};
Test(std::string &&t) : tag(t) {
std::cout << "Move Constructed" << '\n';
};
Test(const Test &other) : tag(other.tag) {
std::cout << "Copyed" << '\n';
};
Test(Test &&rr) : tag(std::move(rr.tag)) {
std::cout << "Moved" << '\n';
};
Test& operator=(const Test& other){
tag = other.tag;
std::cout << "assigned" << '\n';
return *this;
};
};
std::ostream& operator<<(std::ostream& out, const Test& t) {
out << t.tag;
return out;
}
int main() {
std::vector<Test> v;
std::cout << "capacity: " << v.capacity() << '\n';
#ifdef F4
v.reserve(4);
#endif
std::string s("test1");
Test t(s);
v.push_back(t);
std::cout << "capacity: " << v.capacity() << '\n';
std::string s2("test2");
Test t2(s2);
v.push_back(std::move(t2));
std::cout << "capacity: " << v.capacity() << '\n';
v.push_back(Test(std::string("test3")));
std::cout << "capacity: " << v.capacity() << '\n';
std::cout << "List:\n";
for(auto &a:v)
std::cout << a << '\n';
return 0;
}
@junfenglx
Copy link
Author

Compile:

g++ -g -std=c++11 push_back.cc`

@junfenglx
Copy link
Author

Output:

capacity: 0
Constructed
Copyed
capacity: 4
Constructed
Moved
capacity: 4
Move Constructed
Moved
capacity: 4
List:
test1
test2
test3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment