[英]auto from const std::vector<>&; object or reference?
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
变量访问属性:
auto childs = node->getChilds();
what is the type of childs
? 什么类型的
childs
? a std::vector< something >
or a reference to one? 一个
std::vector< something >
或对一个的引用?
The type of childs
will be std::vector<something>
. childs
的类型将为std::vector<something>
。
auto
is powered by the same rules as template type deduction . auto
由与模板类型推导相同的规则提供支持。 The type picked here is the same that would get picked for template <typename T> f(T t);
这里选择的类型与为
template <typename T> f(T t);
选择的类型相同template <typename T> f(T t);
in a call like f(node->getChilds())
. 在像
f(node->getChilds())
这样的调用中。
Similarly, auto&
would get you the same type that would get picked by template <typename T> f(T& t);
同样,
auto&
将为您提供与template <typename T> f(T& t);
相同的类型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);
,而
auto&&
将为您提供与template <typename T> f(T&& t);
. 。
The same applies for all other combinations, like auto const&
or auto*
. 对于所有其他组合,例如
auto const&
或auto*
,同样适用。
It's an std::vector<something>
. 这是一个
std::vector<something>
。 If you want a reference, you can do this: 如果需要参考,可以执行以下操作:
auto & childs = node->getChilds();
That will of course be a const reference. 当然,这将是一个const引用。
auto
gives you std::vector<something>
. auto
为您提供std::vector<something>
。 You can either specify reference qualifier auto &
or, alternatively, you can use decltype
: 您可以指定参考限定词
auto &
,也可以使用decltype
:
decltype( node->getChilds() ) childs = node->getChilds();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.