user2277354
user2277354

Reputation:

manual or automatic type casting in c++

I'm wondering, if I use static_cast rather than let the compiler find out if an object can be casted and do it by itself, may it cost less compilation time or not? Approx. 3000 lines of c++ code I'm taling about. For example:

stack< const something*> myStack;
// ...
myStack.push(/* not const */ something*) 

vs.

stack< const something*> myStack;
// ...
myStack.push(static_cast< const something*>(something*)). 

I've learned ada language in the university and i'm a little confused since then about whether I should do the casting or let the compiler do it.

Upvotes: 2

Views: 988

Answers (2)

Matthieu M.
Matthieu M.

Reputation: 299740

No, it will not save compilation time.

To figure out why, consider:

auto i = /* some expr */;

Versus:

int i = /* some expr */;

The first thing that the compiler need to do, in both cases, is computing the type of some expr. Then, in the auto case it will simply consider the base type to be that of i and in the second case, if the base type is not int, it will check whether there is a valid conversion.

The same thing occurs in your case, whether or not you specify the type explicitly the compiler must compute the type of the expression and must check whether the conversion that occur (whether implicit or not) are allowed.

You are not helping, thus, and you are making the code less readable for yourself and your coworkers by cluttering it.

Upvotes: 0

Andy Prowl
Andy Prowl

Reputation: 126412

The static_cast<> is unnecessary here, because as you guessed, the compiler will perform the qualification conversion itself.

It just makes your (valid) code unnecessarily harder to read, so I would not use it. When I read a static_cast<>, I expect something relevant to be going on that requires that cast, something that is calling for my attention, and require me to go and figure out what is going on and why. This is like a fake alarm.

Prefer making your code easy to read and clean.

And if you have issues with compilation time, I would personally not bother with this kind of micro-optimizations - they might as well increase the compilation time (after all, the compiler needs to check if the static_cast is legal in the first place). Rather, consider whether you could not rethink the design of your classes and of dependencies between them - can't give concrete advices without seeing them though.

Upvotes: 1

Related Questions