//
// Created by light on 19-11-4.
//
#include
#include
#include
using namespace std;
// Rvalue references è§£å³éå¿
è¦çæ·è´ å½èµå¼å³æè¾¹æ¯ä¸ä¸ª"å³å¼",å·¦æè¾¹å¯¹è±¡å¯ä»¥å·å³æè¾¹å¯¹è±¡,èä¸éè¦éæ°åé
å
åã
// æµ
copy
int foo() { return 5; }
class Foo {
public:
Foo() = default;
Foo(const Foo &foo) = default;
Foo(Foo &&foo) noexcept {}
};
// 夿è°ç¨åªä¸ä¸ªå½æ°
void process(int &i) {
cout << "å·¦å¼ä¼ å
¥" << endl;
}
void process(int &&i) {
cout << "å³å¼ä¼ å
¥" << endl;
}
void UnPerfectForward(int &&i) {
cout << "forward(int&& i)" << endl;
process(i);
}
// std::forward()å®ç°å°±æ¯ä¸é¢è¿æ ·
void PerfectForward(int &&i) {
cout << "forward(int&& i)" << endl;
process(static_cast(i));
}
// Lvalue: åé
// Rvalue: 临æ¶å¯¹è±¡å°±æ¯ä¸ªå³å¼,å³å¼ä¸å¯ä»¥æ¾å¨å·¦è¾¹
int main() {
int a = 9, b = 4;
a = b;
b = a;
// a+b=42;// error Rvalue
string s1("hello");
string s2("world");
s1 + s2 = s2; // ok
string() = "ok"; // ok
cout << "s2:" << s1 + s2 << endl;
cout << "s1:" << s1 << endl;
cout << "s2:" << s2 << endl;
complex c1(3, 8), c2(1, 0);
c1 + c2 = complex(3, 4); // ok
complex() = complex(1, 2); // ok
int x = foo();
// int *p=&foo(); //error! Rvalueä¸å¯ä»¥åå°å
// foo()=7; // error
// Rvalue references
// vector vec;
// vec.insert(vec.begin(), Foo()); // Rvalue references and Move Semantics
// åå
æ¯ä¸é¢è¿ä¸ª
// iterator insert(const_iterator __position, const value_type& __x);
// è°ç¨ä¸é¢è¿ä¸ªMove Semantics
// iterator insert(const_iterator __position, value_type&& __x) // ç¶å转交ç»Foo(Foo&& foo)
// { return emplace(__position, std::move(__x)); }
// Foo()è¿ä¸ªä¸´æ¶å¯¹è±¡ä¸ºå³å¼äº¤ç»insertçmove assignmentç¶åå交ç»Fooçmove ctorãä¸é´æå¯è½ä¼ä¸¢å¤±ä¸äºä¿¡æ¯ã
int aa = 1;
process(aa); // L
process(1); // R
process(move(aa)); // R
UnPerfectForward(2); // 叿éè¿è½¬äº¤è°ç¨çæ¯å³å¼ä¼ å
¥å½æ°,坿¯è°ç¨çæ¯å·¦å¼ä¼ å
¥ è¿å°±æ¯ä¸ªUnperfect Forwarding
UnPerfectForward(move(aa)); // åä¸
// é£å¦ä½è®¾è®¡Perfect Forwarding?
// ä¸ºä¼ éå ä¸static_cast强转æè
ç´æ¥ä½¿ç¨std::forward()
PerfectForward(2);
PerfectForward(move(aa));
return 0;
}