c++ - const_cast vs static_cast -
To add const to a non-concrete object, which is the preferred method? const_cast & lt; T & gt; or static_cast & lt; T & gt; In a recent question, someone has mentioned that they prefer to use the static_cast , but I would have thought that the code const_cast is more obvious Will intend So what is the logic of using static_cast to create a variable const?
Start a const reference referenced to the object or not:
T x; CONST T & amp; Xref (x); X.f (); // Call non-construction surcharge xref.f (); // call common overload or, use a implicit_cast function template like:
T x; X.f (); // call non-present overload built-in_state & lt; Const T & amp; & Gt; (X) .f (); Looking at the choice between static_cast and const_cast , static_cast is definitely better: // call const overload const_cast should only be used for abandonment constness because it is the only artist who can do this, and in removing the console Naturally dangerous. Modifying the object through references obtained by removing the pointer or constellation can be undefined behavior.
Comments
Post a Comment