Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 "auto" semantics

Tags:

c++

c++11

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? 
like image 475
Alex B Avatar asked Dec 17 '11 05:12

Alex B


People also ask

Does C++11 have auto?

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.

What is Auto in C++11?

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.

What does decltype auto do?

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.

Can auto be a reference?

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.


1 Answers

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 
like image 82
BЈовић Avatar answered Sep 21 '22 06:09

BЈовић