Question about const_cast in c++

后端 未结 4 581
没有蜡笔的小新
没有蜡笔的小新 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(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
    

提交回复
热议问题