| 1 |
#include <iostream> |
| 2 |
|
| 3 |
using namespace std; |
| 4 |
|
| 5 |
struct VI // define the data structure to |
| 6 |
{ // operate on |
| 7 |
static size_t s_count; |
| 8 |
using value_type = int; |
| 9 |
|
| 10 |
VI() = default; |
| 11 |
|
| 12 |
VI(VI const &other) |
| 13 |
{ |
| 14 |
(*this)[0] = other[0]; |
| 15 |
cout << "CC, count = " << s_count << '\n'; |
| 16 |
} |
| 17 |
|
| 18 |
VI(VI &&tmp) |
| 19 |
{ |
| 20 |
(*this)[0] = tmp[0]; |
| 21 |
cout << "MC, count = " << s_count << '\n'; |
| 22 |
} |
| 23 |
|
| 24 |
int d_value = 0; |
| 25 |
|
| 26 |
size_t size() const |
| 27 |
{ |
| 28 |
return 1; |
| 29 |
}; |
| 30 |
|
| 31 |
VI &operator=(VI const &other) |
| 32 |
{ |
| 33 |
cout << "op=\n"; |
| 34 |
(*this)[0] = other[0]; |
| 35 |
return *this; |
| 36 |
} |
| 37 |
|
| 38 |
VI &operator+=(VI const &other) |
| 39 |
{ |
| 40 |
cout << "op+=\n"; |
| 41 |
(*this)[0] += other[0]; |
| 42 |
return *this; |
| 43 |
} |
| 44 |
|
| 45 |
int &operator[](size_t idx) |
| 46 |
{ |
| 47 |
++s_count; |
| 48 |
return d_value; |
| 49 |
} |
| 50 |
|
| 51 |
int const &operator[](size_t idx) const |
| 52 |
{ |
| 53 |
++s_count; |
| 54 |
return d_value; |
| 55 |
} |
| 56 |
}; |
| 57 |
|
| 58 |
VI operator+(VI const &lhs, VI const &rhs) |
| 59 |
{ |
| 60 |
cout << "copy +\n"; |
| 61 |
VI tmp{lhs}; |
| 62 |
tmp += rhs; |
| 63 |
return tmp; |
| 64 |
} |
| 65 |
|
| 66 |
VI &&operator+(VI &&tmp, VI const &rhs) |
| 67 |
{ |
| 68 |
cout << "move +\n"; |
| 69 |
tmp += rhs; |
| 70 |
return move(tmp); |
| 71 |
} |
| 72 |
|
| 73 |
|
| 74 |
size_t VI::s_count; |
| 75 |
|
| 76 |
|
| 77 |
int main() |
| 78 |
{ |
| 79 |
VI a, b, c, d; |
| 80 |
|
| 81 |
VI e = a + b + c + d; |
| 82 |
|
| 83 |
// 2nd cout avoids the 'not used' compiler warning |
| 84 |
// cout << "# index computations: " << VI::s_count << '\n'; |
| 85 |
cout << "# index computations: " << e.s_count << '\n'; |
| 86 |
} |