[英]If function f() returns a pointer, which is correct: auto* v = f() OR auto v = f()?
I use the c++11 auto
keyword just about everywhere. 我几乎到处都使用c ++ 11 auto
关键字。 I'm not sure if I'm using it correctly in this case though. 我不确定在这种情况下我是否正确使用它。 Consider the following trivial example: ( http://ideone.com/TxLJlx ) 请考虑以下简单示例:( http://ideone.com/TxLJlx )
#include <iostream>
const char* f()
{
return "Hello";
}
int main()
{
auto s1 = f();
auto* s2 = f();
std::cout << s1 << std::endl;
std::cout << s2 << std::endl;
return 0;
}
Both auto
and auto*
seem to work and appear to do the same thing. auto
和auto*
似乎都工作,似乎做同样的事情。 Is this assumption wrong? 这个假设是错的吗?
Why do both give the same results? 为什么两者都给出相同的结果?
Which is the correct use of auto
in this case? 在这种情况下哪个是正确使用auto
?
They both mean the same - the type will be const char*
in both cases. 它们的含义相同 - 两种情况下的类型都是const char*
。 However, using auto *
stresses (and self-documents) the fact that f()
returns a pointer. 但是,使用auto *
stress(和自我文档) f()
返回指针的事实。 And it would signal an error if the function is later changed to return something else (eg std::string
in this case). 如果稍后更改函数以返回其他内容(例如,在这种情况下为std::string
),则会发出错误信号。
Which to use is primarily a matter of style. 使用哪个主要是风格问题。 If the code relies heavily on f()
returning a pointer, or you feel the need to make this obvious, use auto*
. 如果代码在很大程度上依赖于f()
返回一个指针,或者您觉得需要明确这一点,请使用auto*
。 Otherwise, just use auto
and be done with it. 否则,只需使用auto
并完成它。
Note that the case is different when returning references. 请注意,返回引用时的情况不同。 Those are dropped by the auto
deduction, so if you need to take a returned reference as a reference, you have to use auto &
(or use auto &&
to get a universal reference). 这些都是通过auto
扣除来删除的,因此如果您需要将返回的引用作为参考,则必须使用auto &
(或使用auto &&
来获取通用引用)。
auto s1 = f();
You use auto
so that compiler can deduce the appropriate type whenever it can without being bothered about doing so yourself. 您可以使用auto
以便编译器可以随时推断出适当的类型,而不必为此而烦恼。 whether it is a pointer or not is take care of because it is a part of the type so you don't have to be worried about that. 它是否是一个指针是照顾,因为它是该类型的一部分,所以你不必担心这一点。
auto
completes any type for you, if you specified the pointer( *
) all its left is to complete is the char
(or will cause an error if no completion available, for example if f()
return a plain char
). auto
为你完成任何类型的操作,如果指定了指针( *
),其左边的所有内容都是char
(或者如果没有完成可用会导致错误,例如,如果f()
返回一个普通的char
)。
You should bother with the pointer, just use auto
. 你应该打扰指针,只需使用auto
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.