Item 44. Casts
Difficulty: 6
How well do you know
C++'s casts? Using them well can greatly improve the reliability of
your code.
The new-style casts in standard C++ offer more
power and safety than the old-style (C-style) casts. How well do
you know them? The rest of this problem uses the following classes
and global variables:
class A { public: virtual ~A(); /*...*/ };
A::~A() { }
class B : private virtual A { /*...*/ };
class C : public A { /*...*/ };
class D : public B, public C { /*...*/ };
A a1; B b1; C c1; D d1;
const A a2;
const A& ra1 = a1;
const A& ra2 = a2;
char c;
This Item presents four questions.
-
Which of the
following new-style casts are not
equivalent to a C-style cast?
const_cast
dynamic_cast
reinterpret_cast
static_cast
-
For each of the
following C-style casts, write the equivalent new-style cast. Which
are incorrect if not written as a new-style cast?
void f()
{
A* pa; B* pb; C* pc;
pa = (A*)&ra1;
pa = (A*)&a2;
pb = (B*)&c1;
pc = (C*)&d1;
}
-
Critique each
of the following C++ casts for style and correctness.
void g()
{
unsigned char* puc = static_cast<unsigned char*>(&c);
signed char* psc = static_cast<signed char*>(&c);
void* pv = static_cast<void*>(&b1);
B* pb1 = static_cast<B*>(pv);
B* pb2 = static_cast<B*>(&b1);
A* pa1 = const_cast<A*>(&ra1);
A* pa2 = const_cast<A*>(&ra2);
B* pb3 = dynamic_cast<B*>(&c1);
A* pa3 = dynamic_cast<A*>(&b1);
B* pb4 = static_cast<B*>(&d1);
D* pd = static_cast<D*>(pb4);
pa1 = dynamic_cast<A*>(pb2);
pa1 = dynamic_cast<A*>(pb4);
C* pc1 = dynamic_cast<C*>(pb4);
C& rc1 = dynamic_cast<C&>(*pb2);
}
-
Why is it
typically unuseful to const_cast from non-const
to const? Demonstrate a valid example in which it can be
useful to const_cast from non-const to
const.
|