Is const_cast safe?

后端 未结 6 2193
名媛妹妹
名媛妹妹 2020-11-22 12:17

I can\'t find much information on const_cast. The only info I could find (on Stack Overflow) is:

The const_cast<>() i

6条回答
  •  攒了一身酷
    2020-11-22 12:37

    What Adam says. Another example where const_cast can be helpful:

    struct sample {
        T& getT() { 
            return const_cast(static_cast(this)->getT()); 
        }
    
        const T& getT() const { 
           /* possibly much code here */
           return t; 
        }
    
        T t;
    };
    

    We first add const to the type this points to, then we call the const version of getT, and then we remove const from the return type, which is valid since t must be non-const (otherwise, the non-const version of getT couldn't have been called). This can be very useful if you got a large function body and you want to avoid redundant code.

提交回复
热议问题