C++11 "auto"语义

标签 c++ c++11

当我使用 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

关于C++11 "auto"语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8542873/

相关文章:

c++ - 在 vector 的 vector 中找到 Point3f 的最大值

c++ - 我可以为数组编写一个用户定义的推导规则到 vector 吗?

c++ - 嵌套类 C++

c++ - 对 Windows HANDLE 使用 std::unique_ptr

c++ - 在变量或字段 'printVector' 声明为 void 之前缺少模板参数

c++ - 使用 std::string 作为缓冲区有缺点吗?

c++ - 在 C++ 中使用 reinterpret_cast 向下转型

c++ - VS 2017 如何启用装饰?

c++ - 模板类问题

c++ - 用内部 vector 填充结构 vector 的一种优雅/有效的方法