language: C++ 4.7.2 (gcc-4.7.2)
date: 303 days 17 hours ago
link:
visibility: private
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//rvalue classes and move function
template <class T>
struct r_ref {
    mutable T& ref;
    r_ref(T& rhs) :ref(rhs) {}
    r_ref(const r_ref& rhs) :ref(rhs.ref) {}
};
template <class T>
struct r_val : r_ref<T> {
    mutable T val;
    r_val(T& rhs) :r_ref<T>(val), val(rhs) {}
    r_val(const r_ref<T>& rhs) :r_ref<T>(val), val(rhs) {}
};
template <class T>
r_ref<T> move(T& rhs) {return r_ref<T>(rhs);}
 
 
 
 
 
//demo classes
#include <iostream>
#include <string>
class demo {
public:
    std::string data;
    demo() : data("LONG STRING SO NO CHEATS") {std::cout<<"default construct\n";}
    demo(const demo& rhs) : data(rhs.data) {std::cout<<"copy construct\n";}
    demo(const r_ref<demo>& rhs) : data() {data.swap(rhs.ref.data); std::cout<<"move construct\n";}
    demo& operator=(const demo& rhs) {data = rhs.data; std::cout<<"assignment\n"; return *this;}
    demo& operator=(const r_ref<demo>& rhs) {data.swap(rhs.ref.data); std::cout<<"move assignment\n"; return *this;}
    ~demo() {std::cout<<"destruct\n";}
    void prove() const {std::cout<<(void*)data.c_str()<<'\n';}
};
 
r_val<demo> function(const r_ref<demo>& rhs) {
    demo obj(rhs);
    obj.prove();
    return move(obj);
}
 
 
 
//test suite
int main() {
   std::cout << "want default: ";   demo a;
   std::cout << "want VAR1: ";   a.prove();
   std::cout << "want move construct, VAR1, move construct, destruct, move construct, destruct: ";
   //demo b = function(a); //doesn't compile, lvalue isn't rvalue
   demo b = function(move(a));
   std::cout << "want VAR2: ";   a.prove();
   std::cout << "want VAR1: ";    b.prove();
   std::cout << "want assignment: ";   a = b;
   std::cout << "want VAR3: ";   a.prove();
   std::cout << "want VAR1: ";   b.prove();
   std::cout << "want move assign: ";   a = move(b);
   std::cout << "want VAR1: ";   a.prove();
   std::cout << "want VAR3: ";   b.prove();
 
   std::cout << "want 2x destruct: ";
}