簡體   English   中英

C ++ 11“自動”語義

[英]C++11 “auto” semantics

當我使用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?

規則很簡單:這是你如何聲明它。

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

§7.1.6.4 [dcl.spec.auto] p6

一旦根據8.3確定了declarator-id的類型,使用declarator-id聲明的變量的類型是使用模板參數推導的規則從其初始化程序的類型確定的。

這意味着在函數調用期間除了auto模型模板參數推導之外別無其他。

template<class T>
void f(T){} // #1, will also be by-value

template<class T>
void g(T&){} // #2, will always be by-reference

請注意,無論您是傳遞引用還是其他任何內容,#1將始終復制傳遞的參數。 (除非您專門指定模板參數,如f<int&>(intref);

無論你從右側得到什么(“=”)都不是參考。 更具體地說,表達式的結果永遠不是參考。 在這種情況下,請注意示例中結果之間的差異。

#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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM