Alex B Alex B - 1 year ago 92
C++ Question

C++11 "auto" semantics

When I use C++11

, what are the rules of type deduction with regards to whether it will resolve to a value or a reference?

E.g, sometimes it is clear:

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?

Answer Source

The rule is simple : it is how you declare it.

int i = 5;
auto a1 = i;    // value
auto & a2 = i;  // reference

Next example proves it :

#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

The output:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download