DEV Community

Max Pixel
Max Pixel

Posted on • Edited on

Prefer auto* Over auto for Pointer Declarations in C++

Moved to https://m-pixel.com/prefer-auto-over-auto-for-pointer-declarations-in-c/

Top comments (2)

Collapse
 
pgradot profile image
Pierre Gradot • Edited

Hello

Is Related a FConnection, a FConnection&, a FConnection*, or something else?

auto never deduces a reference type. Hence, Related can either be a FConnection or a pointer to FConnection, nothing else.

const auto VarC = new Type{};
const Type* VarD = new Type{};
// these are substantially different in their meaning.
Enter fullscreen mode Exit fullscreen mode

I must admit that this sample tricked me... But it may sound quite logical when you decompose the statement :

  • auto VarC = new Type{}; => VarC is obviously of pointer.
  • adding const => you have a constant pointer.

The reasoning is not symmetrical with explicit type, I grant you that...

it would be beneficial to strictly prohibit yourself and your team from writing statements that cause auto to encapsulate a declaration's *(s)

I think you're right. Hiding pointers behind typedefs is often considered bad practice in C. We may consider that hiding pointers behind auto also as a bad practice too. I will pay attention to in the next months, and I will see if auto* improve readability in my code.

One might argue that you have should avoided raw pointers in the first place, but as an embedded system developer, I know that pointers always find there way out ;)

Collapse
 
mpixel profile image
Max Pixel

Oops! Good catch regarding the reference type. I'll have to fix that in the article.

Thanks for adding the point about that best-practice in C. You're right, it's effectively the same concern. I've always found pointer typedefs to be inconvenient. Certain UE4 subsystems use them a lot.