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

2019-01-15 12:23发布

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++ c++11 auto
3条回答
放荡不羁爱自由
2楼-- · 2019-01-15 12:35

auto gives you std::vector<something>. You can either specify reference qualifier auto & or, alternatively, you can use decltype:

decltype( node->getChilds() ) childs = node->getChilds();
查看更多
女痞
3楼-- · 2019-01-15 12:38

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

查看更多
男人必须洒脱
4楼-- · 2019-01-15 12:39

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.

查看更多
登录 后发表回答