◐ Shell
clean mode source ↗

const_cast conversion - cppreference.com

De cppreference.com

Esta página se ha traducido por ordenador/computador/computadora de la versión en inglés de la Wiki usando Google Translate.

La traducción puede contener errores y palabras aparatosas/incorrectas. Planea sobre el texto para ver la versión original. Puedes ayudar a corregir los errores y mejorar la traducción. Para instrucciones haz clic aquí.

Convierte entre los tipos con diferentes cv-cualificación .

Original:

Converts between types with different cv-qualification.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Sintaxis

const_cast < new_type > ( expression )

Devuelve un valor de tipo new_type .

Original:

Returns a value of type new_type.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Explicación

Sólo las siguientes conversiones se puede hacer con const_cast. En particular, sólo const_cast se puede utilizar para desechar (eliminar) constness o volatilidad .

Original:

Only the following conversions can be done with const_cast. In particular, only const_cast may be used to cast away (remove) constness or volatility.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

1)

Dos punteros posiblemente varios niveles al mismo tipo se pueden convertir entre sí, independientemente de la CV-calificadores en cada nivel .

Original:

Two possibly multilevel pointers to the same type may be converted between each other, regardless of cv-qualifiers at each level.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

2)

lvalue de cualquier tipo T se puede convertir en una referencia lvalue o valor p para la T mismo tipo, más o menos cv-calificado. Del mismo modo, un valor p puede ser convertido a un valor p de referencia más o menos cv-cualificado .

Original:

lvalue of any type T may be converted to a lvalue or rvalue reference to the same type T, more or less cv-qualified. Likewise, an rvalue may be converted to a more or less cv-qualified rvalue reference.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

3)

Las mismas reglas se aplican a los punteros posiblemente varios niveles para los miembros de datos .

Original:

Same rules apply to possibly multilevel pointers to data members.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

4)

valor de puntero nulo se puede convertir en el valor de puntero nulo de new_type

Original:

null pointer value may be converted to the null pointer value of new_type

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Como con todas las expresiones de conversión, el resultado es:

  • Un l-valor si tipo-de-destino es un tipo referencia a l-valor o un tipo referencia r-valor a función (desde C++11);
  • Un x-valor se tipo-de-destino es un tipo referencia r-valor a tipo objeto;
(desde C++11)
  • Un pr-valor en caso contrario.

Notas

Punteros a funciones y punteros a funciones miembro no están sujetos a const_cast

Original:

Pointers to functions and pointers to member functions are not subject to const_cast

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

A pesar de que const_cast podrá eliminar cualquier constness de puntero o de referencia, utilizando el puntero o referencia que resulta escribir en un objeto que se declaró const invoca un comportamiento indefinido .

Original:

Even though const_cast may remove constness from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const invokes undefined behavior.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Palabras clave

const_cast

Ejemplo

#include <iostream>

struct type {
    type() :i(3) {}
    void m1(int v) const {
        // this->i = v;                 // compile error: this is a pointer to const
        const_cast<type*>(this)->i = v; // OK
    }
    int i;
};

int main() 
{
    int i = 3;                    // i is not declared const
    const int& cref_i = i; 
    const_cast<int&>(cref_i) = 4; // OK: modifies i
    std::cout << "i = " << i << '\n';

    type t;
    t.m1(4);
    std::cout << "type::i = " << t.i << '\n';

    const int j = 3; // j is declared const
    int* pj = const_cast<int*>(&j);
    *pj = 4;         // undefined behavior!

    void (type::*mfp)(int) const = &type::m1; // pointer to member function
//  const_cast<void(type::*)(int)>(mfp); // compiler error: const_cast does not
                                         // work on function pointers
}

Salida:

Ver también