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?
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.
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.
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.
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.
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*
.
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.
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