Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto from const std::vector<>&; object or reference?

Tags:

suppose we have an object with the following interface:

struct Node_t {  ... const std::vector< something >& getChilds() const;  } node; 

Now, i access the property with an auto variable like this:

auto childs = node->getChilds(); 

what is the type of childs? a std::vector< something > or a reference to one?

like image 428
lurscher Avatar asked Jan 10 '12 02:01

lurscher


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 the use of auto in vector C++?

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.

How do I use Auto in STL?

The auto keyword is simply asking the compiler to deduce the type of the variable from the initialization. Even a pre-C++0x compiler knows what the type of an (initialization) expression is, and more often than not, you can see that type in error messages.

Can you add to a const vector?

You can't put items into a const vector, the vectors state is the items it holds, and adding items to the vector modifies that state. If you want to append to a vector you must take in a non const ref. Show activity on this post. If you have a const vector it means you can only read the elements from that vector.


2 Answers

The type of childs will be std::vector<something>.

auto is powered by the same rules as template type deduction. The type picked here is the same that would get picked for template <typename T> f(T t); in a call like f(node->getChilds()).

Similarly, auto& would get you the same type that would get picked by template <typename T> f(T& t);, and auto&& would get you the same type that would get picked by template <typename T> f(T&& t);.

The same applies for all other combinations, like auto const& or auto*.

like image 177
R. Martinho Fernandes Avatar answered Oct 24 '22 03:10

R. Martinho Fernandes


It's an std::vector<something>. If you want a reference, you can do this:

auto & childs = node->getChilds(); 

That will of course be a const reference.

like image 37
Benjamin Lindley Avatar answered Oct 24 '22 02:10

Benjamin Lindley