Question about const_cast in c++

后端 未结 4 582
没有蜡笔的小新
没有蜡笔的小新 2020-12-16 02:41

all: this is quoted from Effective C++ 3rd editiion

const_cast is typically used to cast away the constness of objects. It is the only C++-style ca

相关标签:
4条回答
  • 2020-12-16 02:56

    You don't need const_cast to add constness:

    class C;
    C c;
    C const& const_c = c;
    

    The other way around needs a const_cast though

    const C const_c;
    C& c = const_cast<C&>(const_c);
    

    but behavior is undefined if you try to use non-const operations on c.

    By the way, if you don't use a reference, a copy of the object is to be made:

    C d = const_c; // Copies const_c
    
    0 讨论(0)
  • 2020-12-16 02:59

    const_cast can also be used to add constness.

    $5.2.11/3 - "For two pointer types T1 and T2 where
    
    T1 is cv1 , 0 pointer to cv1 , 1 pointer to . . . cv1 ,n − 1 pointer to cv1 ,n T
    and
    T2 is cv2 , 0 pointer to cv2 , 1 pointer to . . . cv2 ,n − 1 pointer to cv2 ,n T
    
    where T is any object type or the void type and where cv1 ,k and cv2 ,k may be different cv-qualifications, an rvalue of type T1 may be explicitly converted to the type T2 using a const_cast. The result of a pointer const_cast refers to the original object.
    

    Consider:

    int *t1 = NULL;  // T = int, cv1, 0 = none
    int * const t2 = const_cast<int * const>(t1);   // T = int, cv2, 0 = const
    

    As per the quote above, the above is fine and it adds constness to t

    But as Herb Sutter says, it probably is not required explicitly to be done most of the times.

    0 讨论(0)
  • 2020-12-16 03:02

    const_cast cannot modify the constness of the value. So it returns a const reference to the value.

    0 讨论(0)
  • 2020-12-16 03:14

    const_cast can only be used to cast to pointers and references. It can't be used to cast to objects. Here's why: if you have a const object you can't make it non-const and vice versa - it's already const, you can't redeclare it. You can only try to access it through a pointer or reference without (or with) const.

    0 讨论(0)
提交回复
热议问题