Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does auto deduce that a type is a pointer?

I am unclear about the usage of auto in a function I am looking over. Given a parameter defined like:

someFunction(const unique_ptr<BSTNode<int>>& node, paramType param) {

the body of the function establishes a local variable like this:

auto *localNode = node.get();

My understanding of auto is that it deduces the type of what is assigned to it at compile time. The docs state that unique_ptr::get() returns a pointer to the object that it manages. Given that fact, why is it necessary to add * to the variable declaration?

like image 820
Alex Bollbach Avatar asked Dec 07 '25 07:12

Alex Bollbach


2 Answers

Using a * to deduce a pointer is unnecessary, but may be desirable. If the code is later changed such that the initializer no longer returns a pointer, the * will cause auto deduction to fail. If the code that uses this variable is designed with a pointer in mind, this may be a good thing.

like image 103
Chris Dodd Avatar answered Dec 09 '25 19:12

Chris Dodd


why is it necessary to add * to the variable declaration?

It's not. The benefit is that it makes it exceedingly obvious to the reader that localNode is a pointer.

like image 28
T.C. Avatar answered Dec 09 '25 19:12

T.C.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!