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?
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?
C++11 introduces the keyword auto as a new type specifier. auto acts as a placeholder for a type to be deduced from the initializer expression of a variable. With auto type deduction enabled, you no longer need to specify a type while declaring a variable.
The auto keyword specifies that the type of the variable that is begin declared will automatically be deduced from its initializer and for functions if their return type is auto then that will be evaluated by return type expression at runtime.
1 The auto and decltype(auto) type-specifiers designate a placeholder type that will be replaced later, either by deduction from an initializer or by explicit specification with a trailing-return-type. The auto type-specifier is also used to signify that a lambda is a generic lambda.
The auto keyword by itself represents a value type, similar to int or char . It can be modified with the const keyword and the & symbol to represent a const type or a reference type, respectively.
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:
value reference value value reference value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With