DEV Community

Max Pixel
Max Pixel

Posted on • Edited on

4

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 (5)

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.

Collapse
 
ksks_mmm_b945b29a5917ea80 profile image
Ksks Mmm
Collapse
 
ksks_mmm_b945b29a5917ea80 profile image
Ksks Mmm

Bhai please calling

Collapse
 
ksks_mmm_b945b29a5917ea80 profile image
Ksks Mmm

mrmxshoil999

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up