Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template <class T>
- swap(T& a, T& b) {
- T tmp(a); // we now have two copies of a
- a = b; // we now have two copies of b (+ discarded a copy of a)
- b = tmp; // we now have two copies of tmp (+ discarded a copy of b)
- }
- template <class T>
- swap(T& a, T& b) {
- T tmp(std::move(a));
- a = std::move(b);
- b = std::move(tmp);
- }
- static_cast<T&&>(t);
- int a = 3; // 3 is a rvalue, does not exist after expression is evaluated
- int b = a; // a is a lvalue, keeps existing after expression is evaluated
- template <class T>
- typename remove_reference<T>::type&&
- std::move(T&& a)
- {
- return a;
- }
- foo(3 * 5); // obviously, you are calling foo with a temporary (rvalue)
- int a = 3 * 5;
- foo(a); // how to tell the compiler to treat `a` as an rvalue?
- foo(std::move(a)); // will call `foo(int&& a)` rather than `foo(int a)` or `foo(int& a)`
- Object Object::operator+ (const Object& rhs) {
- Object temp (*this);
- // logic for adding
- return temp;
- }
- Object& Object::operator+ (Object&& rhs) {
- // logic to modify rhs directly
- return rhs;
- }
- class ResHeavy{ // ResHeavy means heavy resource
- public:
- ResHeavy(int len=10):_upInt(new int[len]),_len(len){
- cout<<"default ctor"<<endl;
- }
- ResHeavy(const ResHeavy& rhs):_upInt(new int[rhs._len]),_len(rhs._len){
- cout<<"copy ctor"<<endl;
- }
- ResHeavy& operator=(const ResHeavy& rhs){
- _upInt.reset(new int[rhs._len]);
- _len = rhs._len;
- cout<<"operator= ctor"<<endl;
- }
- ResHeavy(ResHeavy&& rhs){
- _upInt = std::move(rhs._upInt);
- _len = rhs._len;
- rhs._len = 0;
- cout<<"move ctor"<<endl;
- }
- // check array valid
- bool is_up_valid(){
- return _upInt != nullptr;
- }
- private:
- std::unique_ptr<int[]> _upInt; // heavy array resource
- int _len; // length of int array
- };
- void test_std_move2(){
- ResHeavy rh; // only one int[]
- // operator rh
- // after some operator of rh, it becomes no-use
- // transform it to other object
- ResHeavy rh2 = std::move(rh); // rh becomes invalid
- // show rh, rh2 it valid
- if(rh.is_up_valid())
- cout<<"rh valid"<<endl;
- else
- cout<<"rh invalid"<<endl;
- if(rh2.is_up_valid())
- cout<<"rh2 valid"<<endl;
- else
- cout<<"rh2 invalid"<<endl;
- // new ResHeavy object, created by copy ctor
- ResHeavy rh3(rh2); // two copy of int[]
- if(rh3.is_up_valid())
- cout<<"rh3 valid"<<endl;
- else
- cout<<"rh3 invalid"<<endl;
- }
- default ctor
- move ctor
- rh invalid
- rh2 valid
- copy ctor
- rh3 valid
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement