Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use auto with const and & in C++?

Tags:

I have a method that returns const A &.

If I want to use auto, what is the right way to do it. Is this OK?

const auto &items = someObject.someMethod(); 

I see some people do this:

auto &items = someObject.someMethod(); 

I am not sure which one to use, and what are the differences really...

Edit:

In this case, are these two equivalent?

auto items = someObject.someMethod(); auto &items = someObject.someMethod(); 
like image 206
user2381422 Avatar asked May 29 '13 09:05

user2381422


People also ask

Can const and auto be declared together?

C++ auto auto, const, and references It can be modified with the const keyword and the & symbol to represent a const type or a reference type, respectively. These modifiers can be combined.

What is auto && in C++?

The auto && syntax uses two new features of C++11: The auto part lets the compiler deduce the type based on the context (the return value in this case). This is without any reference qualifications (allowing you to specify whether you want T , T & or T && for a deduced type T ). The && is the new move semantics.

Is auto used in C++?

The auto keyword in C++ automatically detects and assigns a data type to the variable with which it is used. The compiler analyses the variable's data type by looking at its initialization. It is necessary to initialize the variable when declaring it using the auto keyword.

Does const improve performance?

const correctness can't improve performance because const_cast and mutable are in the language, and allow code to conformingly break the rules. This gets even worse in C++11, where your const data may e.g. be a pointer to a std::atomic , meaning the compiler has to respect changes made by other threads.


1 Answers

Even though the two forms are equivalent in this case, I would choose the first form anyway, since it communicates better the fact that your piece of code does not need to modify the state of the object returned by someMethod().

So my advice is to go for this:

const auto &items = someObject.someMethod(); 
like image 99
Andy Prowl Avatar answered Oct 03 '22 22:10

Andy Prowl