问题
Almost a rehash of What's the difference between function(myVar) and (function)myVar?
But I want to know:
What is the name of these variants and are they 'bad'?
type(myVar)
is constructor like syntax, but for a basic type is it the same as doing a C-style cast which is considered bad in C++?
(type)myVar
this one certainly does seem to be a C-style cast and thus must be bad practice?
I've seen some instances where people replace things like (int)a
with int(a)
citing that the C-style version is bad/wrong yet the linked question says they're both the same!
回答1:
What is the name of these variants
type(expr)
is known as a function-style cast.(type)(expr)
is known as a C-style cast.
and are they 'bad'?
Yes. First off, both are semantically completely equivalent. They are “bad” because they aren’t safe – they might be equivalent to a static_cast
, but equally a reinterpret_cast
, and without knowing both type
and the type of expr
it’s impossible to say1. They also disregard access specifiers in some cases (C-style casts allow casting inside a private inheritance hierarchy). Furthermore, they are not as verbose as the explicit C++ style casts, which is a bad thing since casts are usually meant to stand out in C++.
1 Consider int(x)
: Depending on x
’ type, this is either a static_cast
(e.g. auto x = 4.2f;
) or a reinterpret_cast
(e.g. auto x = nullptr;
on an architecture where int
is large enough to hold a pointer).
来源:https://stackoverflow.com/questions/21841521/what-are-the-names-of-typemyvar-and-typemyvar-are-they-both-bad-practice