Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is auto* useful at compile time or is the auto keyword enough?

Tags:

c++

Since the auto keyword gets the class type at compile time I was wondering if there is any efficency at all when using auto* or if there is any particular use for that expression, because auto will already get the pointer type when compiling.

like image 700
Aether Avatar asked Dec 24 '18 21:12

Aether


People also ask

Is Auto determined at compile time?

Even when a variable is declared auto, its type is fixed at compile time.

Should I always use Auto in C++?

Use auto whenever it's hard to say how to write the type at first sight, but the type of the right hand side of an expression is obvious.

Is auto inefficient C++?

Is it faster: The simple answer is Yes, by using it a lot of type conversions could be omitted, however, if not used properly it could become great source of errors.

What is Auto * C++?

The auto keyword directs the compiler to use the initialization expression of a declared variable, or lambda expression parameter, to deduce its type.


2 Answers

None of this “newfangled C++11” has anything to do with efficient compilation, except in very odd corner cases. It’s all there to make it easier for humans to write and comprehend the code. auto* makes it obvious that you have a pointer-typed value, and the compiler only uses it as an additional typecheck criterion, and will issue a diagnostic if the type is not a pointer type – your code is then malformed and it’s a hard error.

I don’t recall offhand if auto* can ever participate as a disambiguator in type deduction, but if it did, that would be the technical reason to use it. Language lawyer, is there a language lawyer on board? :)

Most properly designed projects – even huge ones – should recompile quickly after changes, it’s a matter of proper partitioning of the code and having development builds that leverage such partitioning.

like image 186
Kuba hasn't forgotten Monica Avatar answered Oct 05 '22 23:10

Kuba hasn't forgotten Monica


auto* makes sense in only two cases I can think of.

1) you want to make it clear to the reader that they are dealing with a pointer variable. 2) you want a compile error if what you assign to the auto* variable is not in fact a pointer.

Outside of those cases, the extra * is redundant and plain auto is just as good.

None of this has anything to do with efficiency btw. It doesn't change the final compiled code in the slightest.

like image 41
Jesper Juhl Avatar answered Oct 05 '22 23:10

Jesper Juhl