Skip to content

Instantly share code, notes, and snippets.

@junfenglx
Last active August 29, 2015 14:13
Show Gist options
  • Save junfenglx/df439cb9c5ecd9b3b6f8 to your computer and use it in GitHub Desktop.
Save junfenglx/df439cb9c5ecd9b3b6f8 to your computer and use it in GitHub Desktop.

Revisions

  1. junfeng_hu revised this gist Jan 12, 2015. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions cpp_move_copy.cc
    Original file line number Diff line number Diff line change
    @@ -22,6 +22,7 @@ class Test {
    Test& operator=(const Test& other){
    tag = other.tag;
    std::cout << "assigned" << '\n';
    return *this;
    };
    };
    std::ostream& operator<<(std::ostream& out, const Test& t) {
  2. junfeng_hu renamed this gist Jan 12, 2015. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. junfeng_hu created this gist Jan 12, 2015.
    56 changes: 56 additions & 0 deletions cpp_move_copy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    #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';
    };
    };
    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;
    }