亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

C ++ 11“自動”語義

C ++ 11“自動”語義

C++
素胚勾勒不出你 2019-12-27 09:37:12
當我使用C ++ 11時auto,關于類型歸納將解析為值還是引用的規則是什么?例如,有時很明顯:auto i = v.begin(); // Copy, begin() returns an iterator by value這些不太清楚:const std::shared_ptr<Foo>& get_foo();auto p = get_foo(); // Copy or reference?static std::shared_ptr<Foo> s_foo;auto sp = s_foo; // Copy or reference?std::vector<std::shared_ptr<Foo>> c;for (auto foo: c) { // Copy for every loop iteration?
查看完整描述

3 回答

?
慕森王

TA貢獻1777條經驗 獲得超3個贊

規則很簡單:這就是您聲明的方式。


int i = 5;

auto a1 = i;    // value

auto & a2 = i;  // reference

下一個例子證明了這一點:


#include <typeinfo>

#include <iostream>    


template< typename T >

struct A

{

    static void foo(){ std::cout<< "value" << std::endl; }

};

template< typename T >

struct A< T&>

{

    static void foo(){ std::cout<< "reference" << std::endl; }

};


float& bar()

{

    static float t=5.5;

    return t;

}


int main()

{

    int i = 5;

    int &r = i;


    auto a1 = i;

    auto a2 = r;

    auto a3 = bar();


    A<decltype(i)>::foo();       // value

    A<decltype(r)>::foo();       // reference

    A<decltype(a1)>::foo();      // value

    A<decltype(a2)>::foo();      // value

    A<decltype(bar())>::foo();   // reference

    A<decltype(a3)>::foo();      // value

}

輸出:


value

reference

value

value

reference

value


查看完整回答
反對 回復 2019-12-27
?
慕碼人8056858

TA貢獻1803條經驗 獲得超6個贊

無論您從右側(等于“ =”)獲得什么,都永遠不會成為參考。更具體地說,表達式的結果永遠不會是引用。因此,請注意示例中結果之間的差異。


#include <typeinfo>

#include <iostream>


template< typename T >

struct A

{

    static void foo(){ std::cout<< "value" << std::endl; }

};


template< typename T >

struct A< T&>

{

    static void foo(){ std::cout<< "reference" << std::endl; }

};


float& bar()

{

    static float t=5.5;

    return t;

}


int main()

{

   auto a3 = bar();


   A<decltype(bar())>::foo(); // reference

   A<decltype(a3)>::foo();    // value

}


查看完整回答
反對 回復 2019-12-27
  • 3 回答
  • 0 關注
  • 560 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號