const_cast vs static_cast

后端 未结 4 937
半阙折子戏
半阙折子戏 2020-12-16 17:41

To add const to a non-const object, which is the prefered method? const_cast or static_cast. In a recent question, s

相关标签:
4条回答
  • 2020-12-16 18:05

    You could write your own cast:

    template<class T>
    const T & MakeConst(const T & inValue)
    {
        return inValue;
    }
    
    0 讨论(0)
  • 2020-12-16 18:20

    This is a good use case for an implicit_cast function template.

    0 讨论(0)
  • 2020-12-16 18:21

    Don't use either. Initialize a const reference that refers to the object:

    T x;
    const T& xref(x);
    
    x.f();     // calls non-const overload
    xref.f();  // calls const overload
    

    Or, use an implicit_cast function template, like the one provided in Boost:

    T x;
    
    x.f();                           // calls non-const overload
    implicit_cast<const T&>(x).f();  // calls const overload
    

    Given the choice between static_cast and const_cast, static_cast is definitely preferable: const_cast should only be used to cast away constness because it is the only cast that can do so, and casting away constness is inherently dangerous. Modifying an object via a pointer or reference obtained by casting away constness may result in undefined behavior.

    0 讨论(0)
  • 2020-12-16 18:25

    I'd say static_cast is preferable since it will only allow you to cast from non-const to const (which is safe), and not in the other direction (which is not necessarily safe).

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