Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function-style casts considered harmful?

Tags:

c++

casting

I understand that generally C-style casts are considered harmful. So, given a class Widget

class Widget{
public:
  explicit Widget(Gizmo gizmo);
};

I could call a function like this:

functionThatTakesAWidget((Widget) gizmo);

using a C-style cast. Or I could write it using a function-style cast:

functionThatTakesAWidget(Widget(gizmo));

but this is exactly equivalent. So no better or worse. And If I really wanted to avoid a C-style cast I could write:

functionThatTakesAWidget(static_cast<Widget>(gizmo));

But given a class Doohickey:

class Doohickey {
public:
  Doohickey(Gizmo left_gizmo, Gizmo right_gizmo);
};

I can't avoid writing:

functionThatTakesADoohickey(Doohickey(left_gizmo, right_gizmo));

I assume this is not considered a 'cast' at all? But what is the difference between this and a function-style cast? Why is this OK but a function-style cast is not?

like image 727
user3502661 Avatar asked Jan 29 '26 19:01

user3502661


1 Answers

The reasons for avoiding C-Style casts are:

  • Being explicit about what kind of casting happens, thus making sure no other type actually does.
  • Making casts easier findable.

While the function-style cast looks safer, it's actually a C-style cast in disguise, so it does not really add anything.

The driving reason behind being explicit is letting the compiler assert your assumptions, instead of silently doing (sometimes) the wrong thing.
IMHO, some purists go to far in their zeal though.

like image 169
Deduplicator Avatar answered Jan 31 '26 09:01

Deduplicator



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!