Item 44. Casts

Source: Internet
Author: User
I l @ ve ruboard

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.

  1. Which of the following new-style casts are not equivalent to a C-style cast?

    const_cast dynamic_castreinterpret_caststatic_cast

  2. 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;}

  3. 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);  }

  4. Why is it typically unusefulConst_castFrom non-ConstToConst? Demonstrate a valid example in which it can be usefulConst_castFrom non-ConstToConst.

 
I l @ ve ruboard

I l @ ve ruboard

Solution

Let's answer the questions one by one.

  1. Which of the following new-style casts are not equivalent to a C-style cast?

    OnlyDynamic_castIs not equivalent to a C-style cast. All other new-style casts have old-style equivalents.

    Guideline

    Prefer new-style casts.

  2. 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;

    UseConst_castInstead:

    pa = const_cast<A*>(&ra1); pa = (A*)&a2;

    This cannot be expressed as a new-style cast. The closest candidate isConst_cast, But becauseA2IsConstObject, the results of using the pointer are undefined.

    pb = (B*)&c1; 

    UseReinterpret_castInstead:

      pb = reinterpret_cast<B*>(&c1);   pc = (C*)&d1;}

    The above cast is wrong in C. In C ++, no cast is required:

    pc = &d1; 

  3. Critique each of the following C ++ casts for style and correctness.

    First, a general note: All of the followingDynamic_castS wocould be errors if the classes involved did not have virtual functions. Fortunately,ADoes provide a virtual function, making allDynamic_castS legal.

    void g() {  unsigned char* puc = static_cast<unsigned char*>(&c);  signed char* psc = static_cast<signed char*>(&c);

    Error: we must useReinterpret_castFor both cases. This might surprise you at first, but the reason is thatChar,Signed Char, AndUnsigned charAre three distinct types. Even though there are implicit conversions between them, they are unrelated, so pointers to them are unrelated.

    void* pv = static_cast<void*> (&b1); B* pb1 = static_cast<B*>(pv);

    These are both fine, but the first is unnecessary, because there is already an implicit conversion from a data pointer toVoid *.

    B* pb2 = static_cast<B*> (&b1); 

    This is fine, but unnecessary, since the argument is alreadyB *.

    A* pa1 = const_cast<A*>(&ra1); 

    This is legal, but casting awayConst(OrVolatile) Is usually indicative of poor style. Most of the cases in which you legitimately wowould want to removeConst-Ness of a pointer or reference are related to class members and covered byMutableKeyword. See item 43 for further discussionConst-Correctness.

    Guideline

    Avoid casting awayConst. UseMutableInstead.

    A* pa2 = const_cast<A*>(&ra2); 

    Error: this will produce undefined behavior if the pointer is used to write on the object, becauseA2Really isConstObject. To see why this is a legitimate problem, consider that a compiler is allowed to see thatA2Is created asConstObject and use that information to store it in read-only memory as an optimization. casting awayConstOn such an object is obviously dangerous.

    Guideline

    Avoid casting awayConst.

    B* pb3 = dynamic_cast<B*>(&c1); 

    Potential error (if you try to usePB3): BecauseC1IS-NOT-AB(BecauseCIs not publicly derived fromBLimit n fact, it is not derived fromBAt all), this will setPB3To null. The only legal cast wocould beReinterpret_cast, And using that is almost always edevil.

    A* pa3 = dynamic_cast<A*>(&b1); 

    Probable error: BecauseB1Is-not-A(BecauseBIs not publicly derived fromA; Its derivation is private), this is illegal unlessG ()Is a friendB.

    B* pb4 = static_cast<B*>(&d1); 

    This is fine, but unnecessary because derived-to-public-base pointer conversions can be done implicitly.

    D* pd = static_cast<D*>(pb4); 

    This is fine, which may surprise you if you expected this to requireDynamic_cast. The reason is that downcasts can be static when the target is known, but beware: You are telling the compiler that you know for a fact that what is being pointed to really is of that type. if you are wrong, then the cast cannot inform you of the problem (as cocouldDynamic_cast, Which wocould return a null pointer if the cast failed) and, at best, you will get spurious run-time errors and/or program crashes.

    Guideline

    Avoid downcasts.

    pa1 = dynamic_cast<A*>(pb2); pa1 = dynamic_cast<A*>(pb4);

    These two look very similar. Both attempt to useDynamic_castTo convertB *IntoA *. However, the first is an error, while the second is not.

    Here's the reason: As noted above, you cannot useDynamic_castTo cast a pointer to what really isBObject (and herePBSPoints to the objectB1) IntoAObject, becauseBInherits privately, not publicly, fromA. However, the second cast succeeds becausePb4Points to the objectD1, AndDDoes haveAAs an indirect public base class (throughC), AndDynamic_castIs able to cast against ss the inheritance hierarchy using the pathB * D * C * A *.

    C* pc1 = dynamic_cast<C*>(pb4); 

    This, too, is fine for the same reason as the last:Dynamic_castCan navigate the inheritance hierarchy and perform cross-casts, so this is legal and will succeed.

      C& rc1 = dynamic_cast<C&>(*pb2); }

    Finally, an "exceptional" error: Because* PBSIsn' t reallyC,Dynamic_castWill throwBad_castException to signal failure. Why? Well,Dynamic_castCan and does return NULL if a pointer cast fails, but since there's no such thing as a null reference, it can't return a null reference if a reference cast fails. there's no way to signal such a failure to the client code besides throwing an exception, so that's what the standardBad_castException class is.

  4. Why is it normally unusefulConst_castFrom non-ConstToConst?

    The first three questions has ded no examples of usingConst_castTo addConst, For example, to convert a pointer to non-ConstTo a pointerConst. After all, explicitly addingConstIs usually redundant failed or example, it's already legal to assign a pointer to non-ConstTo a pointerConst. Normally, we only needConst_castTo do the reverse.

And the last part of the question: demonstrate a valid example where it can be usefulConst_castFrom non-ConstToConst.

There is at least one case in which you cocould usefullyConst_castFrom non-ConstToConstExplain o call a specific overloaded function or a specific version of a template. For example:

void f( T& ); void f( const T& );template<class T> void g( T& t ){  f( t );                       // calls f(T&)  f( const_cast<const T&>(t) ); // calls f(const T&)}

Of course, in the case of choosing a specific version of a template, it's usually just easier to name it explicitly instead of forcing the right deduction. for example, to call the right version of a templated FunctionH (), Writing"H <const T &> (t)"Is preferable to writing"H (const_cast <const T &> (t ))".

 
I l @ ve ruboard

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.