1 auto 會(huì)自動(dòng)把 引用 去除掉
int& get();
auto k = get(); // k的類型是int,而不是int&
Derived object;
auto& same_object = (Base&)object;
auto another_object = (Base&)object; //會(huì)重新構(gòu)造個(gè)Base對(duì)象
2 decltype 有時(shí)會(huì)自動(dòng)把 引用 加上
int x;
decltype((x)) 和 decltype(*&x) 的類型是int&,而不是int
在宏中使用decltype時(shí),要特別注意別多加了括號(hào)。
下面這段代碼錯(cuò)在哪里?
template<typename T, typename R>
auto min(T t, R r) -> decltype(t < r ? t : r)
{
return (t < r ? t : r);
}
decltype(t < r ? t : r)的類型是T&或R&,而不是所希望的T或R!
標(biāo)準(zhǔn)是這樣規(guī)定的:
The type denoted by decltype(e) is defined as follows:
— if e is an unparenthesized id-expression or an unparenthesized class member
access (5.2.5), decltype(e) is the type of the entity named by e. If there
is no such entity, or if e names a set of overloaded functions, the program
is ill-formed;
— otherwise, if e is an xvalue, decltype(e) is T&&, where T is the type of e;
— otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;
— otherwise, decltype(e) is the type of e.
3 std::move、std::forward、右值引用
C++11 引入 右值引用,可以做到:函數(shù)轉(zhuǎn)發(fā)、針對(duì)臨時(shí)對(duì)象優(yōu)化
move是動(dòng)詞,從字面上理解好像是要移動(dòng)對(duì)象,其實(shí)std::move只是簡(jiǎn)單的將類型轉(zhuǎn)成右值引用而已?。。?可以理解成 cast_to_rvalue_reference 或 treat_as_temporal_object。
void test1(int&&) {}
void test2(int&& value) //注意:value的類型是int,而不是int&&
{
test1(value); //無(wú)法編譯通過(guò),因?yàn)関alue的類型是int! 必須轉(zhuǎn)換類型
test1(static_cast<int&&>(value)); //或者
test1(std::forward<int>(value));
}
test2函數(shù)中,value的類型是int,而不是int&&。
這是一個(gè)不得已的選擇。如果value的類型是int&&的話,就會(huì)有副作用:
void increase(int& value) { ++value; }
void test3(int&& value) { increase(value); }
char ch = 'a';
test3(ch); //本意是改變ch值,但實(shí)際上ch值不會(huì)改變,改變的是臨時(shí)對(duì)像
通過(guò)轉(zhuǎn)發(fā)函數(shù)test3,increase函數(shù)可以修改臨時(shí)對(duì)像,
這造成程序員犯的錯(cuò)誤(如上面的例子),難以在編譯時(shí)就被找出來(lái)。
std::forward<T>(value) 等價(jià)于 static_cast<T&&>(value),感覺(jué)后者更容易理解。
std::forward 起到的轉(zhuǎn)發(fā)作用。如果T類型為 R&、 R&&,經(jīng)過(guò)類型轉(zhuǎn)換后,其類型還是和原來(lái)的一樣。
在C++11中
R& & 等同于 R& (在c++03中,R& &這種寫法是非法的)
R&& & 等同于 R&
R& && 等同于 R&
R&& && 等同于 R&&