example3_move_semantics.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <utility>
#include <iostream>
#include <vector>
#include <string>

class Resource {
public:
    Resource(const std::string& s) : data(s) {
        std::cout << "Constructor called for " << data << std::endl;
    }
    Resource(const Resource& other) : data(other.data) {
        std::cout << "Copy constructor called for " << data << std::endl;
    }
    Resource(Resource&& other) noexcept : data(std::move(other.data)) {
        std::cout << "Move constructor called for " << data << std::endl;
    }
    ~Resource() {
        std::cout << "Destructor called for " << data << std::endl;
    }

private:
    std::string data;
};

int main() {
    std::vector<Resource> resources;

    std::cout << "Adding Resource without move:" << std::endl;
    Resource r1("Resource 1");
    resources.push_back(r1);

    std::cout << "\nAdding Resource with move:" << std::endl;
    Resource r2("Resource 2");
    resources.push_back(std::move(r2));

    std::cout << "\nEnd of main" << std::endl;
    return 0;
}
Back to utility