Espacios de nombres
Variantes
Acciones

Conversión reinterpret_cast

De cppreference.com
< cpp‎ | language
 
 
Lenguaje C++
Temas generales
Control de flujo
Instrucciones de ejecución condicionales
Instrucciones de iteración (bucles)
Declaraciones de salto
Funciones
Declaración de funciones
Declaración de funciones lambda
Especificador inline
Especificación de excepciones(hasta C++20)
Especificador noexcept(C++11)
Excepciones
Espacios de nombres
Tipos
Especificadores
decltype(C++11)
auto(C++11)
alignas(C++11)
Especificadores de duración de almacenamiento
Inicialización
Expresiones
Representaciones alternas
Literales
Booleanos - Enteros - De punto flotante
De carácter - De cadena - nullptr(C++11)
Definidos por el usuario(C++11)
Utilidades
Atributos(C++11)
Tipos
Declaración de typedef
Declaración de alias de tipo(C++11)
Conversiones
Conversiones implícitas - Conversiones explícitas
static_cast - dynamic_cast
const_cast - reinterpret_cast
Asignación de memoria
Clases
Propiedades de funciones específicas de la clase
Funciones miembro especiales
Plantillas
Misceláneos
 
Convierte entre distintos tipos de reinterpretar el patrón de bits subyacente .
Original:
Converts between types by reinterpreting the underlying bit pattern.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Contenido

[editar]Sintaxis

reinterpret_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.

[editar]Explicación

A diferencia de static_cast, pero como const_cast, la expresión reinterpret_cast no compila todas las instrucciones de la CPU. Es puramente una directiva del compilador que indica al compilador que trate la secuencia de bits (representación de objetos) de expression como si tuviera el tipo new_type .
Original:
Unlike static_cast, but like const_cast, the reinterpret_cast expression does not compile to any CPU instructions. It is purely a compiler directive which instructs the compiler to treat the sequence of bits (object representation) of expression as if it had the 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.
Sólo las siguientes conversiones se puede hacer con reintepret_cast, excepto cuando tales conversiones sería desechado constness''' o volatilidad .
Original:
Only the following conversions can be done with reintepret_cast, except when such conversions would cast away 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)
Una expresión de enumeración integral, puntero, o puntero a miembro tipo se puede convertir a su propio tipo. El valor resultante es el mismo que el valor de expression. (desde C++11)
Original:
An expression of integral, enumeration, pointer, or pointer-to-member type can be converted to its own type. The resulting value is the same as the value of expression. (desde C++11)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
2)
Cualquier puntero se puede convertir en cualquier tipo integral lo suficientemente grande como para mantener el valor del puntero (por ejemplo, a std::uintptr_t)
Original:
Any pointer can be converted to any integral type large enough to hold the value of the pointer (e.g. to std::uintptr_t)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
3)
Un valor de cualquier tipo integral o de enumeración se puede convertir en un tipo de puntero. Un puntero convertir en un entero de tamaño suficiente y de nuevo al tipo de puntero mismo está garantizado que tenga su valor original, de lo contrario el puntero resultante no puede dejar de hacer referencia de forma segura. El NULL puntero nulo constante o cero entero no está garantizado para dar el valor de puntero nulo del tipo de destino; static_cast o <div class="t-tr-text">conversión implícita
Original:
implicit conversion
The text has been machine-translated via [http://translate.google.com Google Translate].
You can help to correct and verify the translation. Click [http://en.cppreference.com/w/Cppreference:MachineTranslations here] for instructions.
se debe utilizar para este propósito .
Original:
A value of any integral or enumeration type can be converted to a pointer type. A pointer converted to an integer of sufficient size and back to the same pointer type is guaranteed to have its original value, otherwise the resulting pointer cannot be dereferenced safely. The null pointer constant NULL or integer zero is not guaranteed to yield the null pointer value of the target type; static_cast or
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
4)
Cualquier valor de std::nullptr_t tipo, incluyendo nullptr se puede convertir en cualquier tipo integral, como si fuera (void*)0, pero ningún valor, ni siquiera nullptr se puede convertir en std::nullptr_t: static_cast debe utilizarse para ese propósito. (desde C++11)
Original:
Any value of type std::nullptr_t, including nullptr can be converted to any integral type as if it was (void*)0, but no value, not even nullptr can be converted to std::nullptr_t: static_cast should be used for that purpose. (desde C++11)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
5)
Cualquier puntero al objeto de T1 tipo se puede convertir a puntero a objeto de otro tipo T2. Si el requisito T2 de alineación no es más estricta que T1, la conversión del puntero resultante de nuevo a sus rendimientos de tipo de original del valor original, de lo contrario el puntero resultante no puede dejar de hacer referencia de forma segura. En cualquier caso, el puntero resultante sólo puede dejar de hacer referencia de manera segura si es permitido por las reglas de tipo' aliasing (ver más abajo)
Original:
Any pointer to object of type T1 can be converted to pointer to object of another type T2. If T2's alignment requirement is not stricter than T1's, conversion of the resulting pointer back to its original type yields the original value, otherwise the resulting pointer cannot be dereferenced safely. In any case, the resulting pointer may only be dereferenced safely if allowed by the type aliasing rules (see below)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
6)
Una expresión lvalue de T1 tipo se puede convertir para hacer referencia a otro tipo T2. El resultado es un valor-o refiriéndose al mismo objeto que el original lvalue, pero con un tipo diferente xValue. Sin temporal se crea ninguna copia se hace, ningún constructor o funciones de conversión son llamados. La referencia de resultado sólo se puede acceder con seguridad si es permitido por las reglas de tipo' aliasing (ver más abajo)
Original:
An lvalue expression of type T1 can be converted to reference to another type T2. The result is an lvalue or xvalue referring to the same object as the original lvalue, but with a different type. No temporary is created, no copy is made, no constructors or conversion functions are called. The resulting reference can only be accessed safely if allowed by the type aliasing rules (see below)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
7)
Cualquier puntero a la función se puede convertir en un puntero a un tipo de función diferente. Llamar a la función a través de un puntero a un tipo diferente función no está definida, pero la conversión de puntero de nuevo a tal indicador al tipo de función original se obtiene el puntero a la función original .
Original:
Any pointer to function can be converted to a pointer to a different function type. Calling the function through a pointer to a different function type is undefined, but converting such pointer back to pointer to the original function type yields the pointer to the original function.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
8)
En algunas implementaciones (en particular, en cualquier sistema POSIX compatible), un puntero de función se pueden convertir a un puntero de objeto o viceversa. Si la aplicación admite la conversión en ambas direcciones, la conversión al tipo original se obtiene el valor original, de lo contrario el puntero resultante no puede dejar de hacer referencia o llamados de forma segura .
Original:
On some implementations (in particular, on any POSIX compatible system), a function pointer can be converted to an object pointer or vice versa. If the implementation supports conversion in both directions, conversion to the original type yields the original value, otherwise the resulting pointer cannot be dereferenced or called safely.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
9)
El valor de puntero nulo de cualquier tipo de puntero se puede convertir en cualquier otro tipo de puntero, lo que resulta en el valor de puntero nulo de ese tipo. Tenga en cuenta que la nullptr puntero nulo constante o cualquier otro valor de std::nullptr_t tipo no se puede convertir a un puntero con reinterpret_cast: conversión implícita o static_cast se debe utilizar para este propósito .
Original:
The null pointer value of any pointer type can be converted to any other pointer type, resulting in the null pointer value of that type. Note that the null pointer constant nullptr or any other value of type std::nullptr_t cannot be converted to a pointer with reinterpret_cast: implicit conversion or static_cast should be used for this purpose.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
10)
Un puntero a la función miembro rvalue se puede convertir a puntero a una función miembro diferente de un tipo diferente. Conversión al tipo original produce el valor original, de lo contrario el puntero resultante no puede ser utilizado con seguridad .
Original:
An rvalue pointer to member function can be converted to pointer to a different member function of a different type. Conversion to the original type yields the original value, otherwise the resulting pointer cannot be used safely.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
11)
Un puntero a objeto rvalue miembro de alguna T1 clase puede convertirse en un puntero a otro objeto miembro de otra clase T2. Si la alineación T2 no es más estricta que T1, la conversión a los rendimientos de tipo de original del valor original, de lo contrario el puntero resultante no puede ser utilizado con seguridad .
Original:
An rvalue pointer to member object of some class T1 can be converted to a pointer to another member object of another class T2. If T2's alignment is not stricter than T1's, conversion to the original type yields the original value, otherwise the resulting pointer cannot be used safely.
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.

[editar]Palabras clave

reinterpret_cast

[editar]Alias de tipos

Cuando se intenta leer o modificar el valor almacenado de un objeto de tipo DynamicType a través de un glvalue de tipo AliasedType, el comportamiento está indefinido a menos que uno de los siguientes sea verdadero:

  • AliasedType y DynamicType son similares.
  • AliasedType es la la variante (posiblemente calificada-cv) con signo o sin signo de DynamicType.
  • AliasedType es std::byte(desde C++17), char, o unsignedchar: esto permite el examen de la representación de objeto de cualquier objeto como un array de bytes.

Informalmente, dos tipos son similares si, ignorando la calificación-cv de nivel superior:

  • son del mismo tipo; o
  • ambos son punteros, y los tipos apuntados son similares; o
  • ambos son punteros a miembro de la misma clase, y los tipos de los miembros a los que se apunta son similares; o
  • ambos son arrays del mismo tamaño o ambos arrays de límite desconocido, y los tipos del elemento de los arrays son similares.
(hasta C++20)
  • ambos son arrays del mismo tamaño o al menos uno de ellos es un array de límite desconocido, y los tipos de los elementos de los arrays son similares.
(desde C++20)

Por ejemplo:

  • constint*volatile* y int**const son similares;
  • constint(*volatile S::*const)[20] y int(*const S::*volatile)[20] son similares;
  • int(*const*)(int*) y int(*volatile*)(int*) son similares;
  • int(S::*)()const y int(S::*)() no son similares;
  • int(*)(int*) y int(*)(constint*) no son similares;
  • constint(*)(int*) y int(*)(int*) no son similares;
  • int(*)(int*const) y int(*)(int*) son similares (son del mismo tipo);
  • std::pair<int, int> y std::pair<constint, int> no son similares.

Esta regla habilita el análisis de alias basado en tipo, en el que un compilador supone que el valor leído a través de un glvalue de un tipo no se modifica por una escritura a un glvalue de un tipo diferente (sujeto a las excepciones mencionadas anteriormente).

Observa que varios compiladores de C++ relajan esta regla como una extensión no estándar del lenguaje para permitir el acceso al tipo equivocado a través del miembro inactivo de una unión (tal acceso no está indefinido en C).

[editar]Ejemplo

Muestra algunos usos de reinterpret_cast:
Original:
Demonstrates some uses of reinterpret_cast:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

#include <cstdint>#include <cassert>#include <iostream>int f(){return42;}int main(){int i =7;   // pointer to integer and back uintptr_t v1 =reinterpret_cast<uintptr_t>(&i);// static_cast is an errorstd::cout<<"The value of &i is 0x"<<std::hex<< v1 <<'\n';int* p1 =reinterpret_cast<int*>(v1);assert(p1 ==&i);   // pointer to function to another and backvoid(*fp1)()=reinterpret_cast<void(*)()>(f);// fp1(); undefined behaviorint(*fp2)()=reinterpret_cast<int(*)()>(fp1);std::cout<<std::dec<< fp2()<<'\n';// safe   // type aliasing through pointerchar* p2 =reinterpret_cast<char*>(&i);if(p2[0]=='\x7')std::cout<<"This system is little-endian\n";elsestd::cout<<"This system is big-endian\n";   // type aliasing through referencereinterpret_cast<unsignedint&>(i)=42;std::cout<< i <<'\n';}

Salida:

The value of &i is 0x7fff352c3580 42 This system is little-endian 42

[editar]Ver también

const_cast conversión
agrega o quita const
Original:
adds or removes const
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[editar]
static_cast conversión
realiza conversiones básicas
Original:
performs basic conversions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[editar]
dynamic_cast conversión
realiza conversiones marcadas polimórficos
Original:
performs checked polymorphic conversions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[editar]
close