C ++ 11“auto”语义 [英] C++11 "auto" semantics

查看:228
本文介绍了C ++ 11“auto”语义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用C ++ 11 auto 时,关于是否会解析为值或引用,类型扣除的规则是什么?

When I use C++11 auto, what are the rules of type deduction with regards to whether it will resolve to a value or a reference?

例如,有时很清楚:

auto i = v.begin(); // Copy, begin() returns an iterator by value



These are less clear:

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

这篇关于C ++ 11“auto”语义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆