开发者

Which cast style is better and why?

Imagine in C++ two classes one named derived and another named base that is a base class of the first. If I had the following code, which is preferred:

base *b = init_value_here;
const derived *d = s开发者_如何学JAVAtatic_cast<derived *>(b);

or

base *b = init_value_here;
const derived *d = static_cast<const derived *>(b);

In other words, is it better to exclude const in the static cast when not required since the compiler can promote to constness, or is it better to include it to loosen the restrictions on b such that it could be made const in the future more readily?


Neither one if possible. Design your class so that the base class defines a fully useful interface and use only the base class pointer.

Sometimes however you're stuck with legacy code, in which case I would explicitly spell out that you're casting it to const.

EDIT: I should make it clear that there are occasionally cases where a non-polymorphic situation arises and a solution using a cast would be appropriate. Generally speaking downcasting may be a design smell but it doesn't always indicate that something is definitely wrong.


I strive to do the least number of explicit casts possible, and everything else implicit, if possible.

So I would use the former (i.e not including const in the cast).

But this is only my opinion. You may be of the opinion to write the const there too, as it fits your taste.


Well, to be clear, they do the same thing.

Now, if you were converting from a const base * to a const derived *, only the latter would be valid, and the former would require a const_cast as well. If you were converting from a base * to a derived *, only the former would be valid, since otherwise you'd need to cast away the const-ness that your cast just added.

My preference would be to avoid using const modifiers in a cast unless explicitly needed. Keep the code as simple as the compiler allows, in other words.

Of course, you should be using dynamic_cast<> rather than static_cast<> in this scenario, if b could be an instance of another derived class.


For just a line of code I wouldn't worry about it much. If you do change b to const base* in future then the compiler will tell you exactly what line is problematic and what to change. So the benefits are pretty minimal either way - one of them makes the line shorter, the other one might save you a few seconds' work in future on an occasion when you're already in that same function changing the code. I'd put the const in if it occurred to me to do so, since it slightly reduces the reliance of one line of code on the details of another line. But I wouldn't go out of my way to change it if the code was already written.

If you're designing an API, then you'd put const where you can, because changing an API might be painful. I don't think this potential future change is painful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜