Espacios de nombres
Variantes
Acciones

reference initialization

De cppreference.com
< cpp‎ | language

 
 
Lenguaje C++
Los temas generales
Original:
General topics
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Control de flujo
Original:
Flow control
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Sentencias condicionales ejecución
Original:
Conditional execution statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Instrucciones de iteración
Original:
Iteration statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Ir declaraciones
Original:
Jump statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Funciones
Original:
Functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
declaración de la función
lambda declaración de la función
función de plantilla
especificador inline
especificaciones de excepción (obsoleto)
noexcept especificador (C++11)
Excepciones
Original:
Exceptions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Los espacios de nombres
Original:
Namespaces
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Tipos
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
decltype specifier (C++11)
Los especificadores
Original:
Specifiers
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
cv especificadores
almacenamiento duración especificadores
constexpr especificador (C++11)
auto especificador (C++11)
alignas especificador (C++11)
Inicialización
Original:
Initialization
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Los literales
Original:
Literals
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Expresiones
Original:
Expressions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
representaciones alternativas
Utilidades
Original:
Utilities
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Tipos
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
typedef declaration
alias de tipo de declaración (C++11)
atributos (C++11)
Lanza
Original:
Casts
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
conversiones implícitas
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-cast estilo y funcional
De asignación de memoria
Original:
Memory allocation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Clases
Original:
Classes
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Clase propiedades específicas de la función
Original:
Class-specific function properties
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Funciones especiales miembro
Original:
Special member functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Plantillas
Original:
Templates
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
clase de plantilla
función de plantilla
plantilla de especialización
paquetes de parámetros (C++11)
Varios
Original:
Miscellaneous
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Montaje en línea
 
Se liga una referencia a un objeto
Original:
Binds a reference to an object
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

T & ref = object ;

T & ref ( object ) ;

T & ref { object } ;

(1)
T && ref = object ;

T && ref ( object ) ;

T && ref { object } ;

(2) (desde C++11)
R fn ( T & arg );

or

R fn ( T && arg );

fn ( object )

(3)
T & fn () {

or

T && fn () {

return object ;

(4)

[editar] Explicación

Una referencia a T se puede inicializar con un objeto de T tipo, en función del tipo T o un objeto implícitamente convertible a T. Una vez inicializado, una referencia no se puede cambiar para hacer referencia a otro objeto .
Original:
A reference to T can be initialized with an object of type T, a function of type T, or an object implicitly convertible to T. Once initialized, a reference cannot be changed to refer to another object.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Las referencias se inicializan en las siguientes situaciones:
Original:
References are initialized in the following situations:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
1)
Cuando una llamada lvalue variable de referencia se declara con un inicializador
Original:
When a named lvalue reference variable is declared with an initializer
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
2)
Cuando una variable rvalue referencia con nombre se declara con un inicializador
Original:
When a named rvalue reference variable is declared with an initializer
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
3)
En una expresión de llamada a la función, cuando el parámetro de la función tiene un tipo de referencia
Original:
In a function call expression, when the function parameter has reference type
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
4)
En la declaración return, cuando la función devuelve un tipo de referencia
Original:
In the return statement, when the function returns a reference type
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Los efectos de la inicialización de referencia son:
Original:
The effects of reference initialization are:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • Si la referencia es una referencia de valor-I:
    Original:
    If the reference is an lvalue reference:
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Si object es una expresión de valor-i, y su tipo es T o una base de T, y es igual o menos cv-calificado, entonces la referencia se enlaza con el objeto identificado por el valor-i o el subobjeto clase base del objeto .
    Original:
    If object is an lvalue expression, and its type is T or a base of T, and is equally or less cv-qualified, then the reference is bound to the object identified by the lvalue or the base class subobject of the object.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Si object es una expresión de valor-, y su tipo es implícitamente convertible a un tipo que es o T o una base de T, igual o menos cv-calificado, entonces las funciones de conversión no explícitas del tipo de fuente y sus clases base que volver referencias lvalue son considerados y el mejor es seleccionado por resolución de sobrecarga. La referencia se enlaza al objeto identificado por el valor-devuelto por la función de conversión (o el subobjeto de clase base)
    Original:
    If object is an lvalue expression, and its type is implicitly convertible to a type that is either T or a base of T, equally or less cv-qualified, then the non-explicit conversion functions of the source type and its base classes that return lvalue references are considered and the best one is selected by overload resolution. The reference is then bound to the object identified by the lvalue returned by the conversion function (or its base class subobject)
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • De lo contrario, si la referencia es o bien rvalue de referencia o de referencia lvalue a const:
    Original:
    Otherwise, if the reference is either rvalue reference or lvalue reference to const:
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Si object es un xValue, un prvalue clase, un prvalue matriz, o un tipo de función lvalue que es ya sea T o una base de T, igual o menos cv-calificado, entonces la referencia se enlaza con el valor de la expresión del inicializador o su base de subobjeto .
    Original:
    If object is an xvalue, a class prvalue, an array prvalue, or a function lvalue type that is either T or a base of T, equally or less cv-qualified, then the reference is bound to the value of the initializer expression or its base subobject.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Si object es una expresión de tipo de clase que puede convertirse implícitamente a una xValue, un prvalue clase, o un valor en función del tipo que es o T o una base de T, igual o menos cv-calificado, entonces la referencia está vinculada a la resultado de la conversión o el subobjeto base .
    Original:
    If object is a class type expression that can be implicitly converted to an xvalue, a class prvalue, or a function value of type that is either T or a base of T, equally or less cv-qualified, then the reference is bound to the result of the conversion or its base subobject.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • De lo contrario, un temporal de T tipo se construye y copia inicializada de object. La referencia se enlaza a este temporal .
    Original:
    Otherwise, a temporary of type T is constructed and copia inicializada from object. The reference is then bound to this temporary.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

[editar] Vida de un temporal

Siempre que una referencia se enlaza a un temporal o a un subobjeto base de un temporal, el tiempo de vida de la temporal se extiende para que coincida con el tiempo de vida de la referencia, con las siguientes excepciones:
Original:
Whenever a reference is bound to a temporary or to a base subobject of a temporary, the lifetime of the temporary is extended to match the lifetime of the reference, with the following exceptions:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • un temporal unido a un valor de retorno de una función en un comunicado return no se extiende: se destruye inmediatamente al final de la expresión de retorno. Esta función siempre devuelve una referencia colgando .
    Original:
    a temporary bound to a return value of a function in a return statement is not extended: it is destroyed immediately at the end of the return expression. Such function always returns a dangling reference.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • un temporal unido a un elemento de referencia en un inicializador lista constructor persiste sólo hasta las salidas de constructor, no tan largo como el objeto existe .
    Original:
    a temporary bound to a reference member in a constructor inicializador lista persists only until the constructor exits, not as long as the object exists.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • un temporal enlazado a un parámetro de referencia en una llamada de función existe hasta el final de la expresión completa que contiene dicha llamada de función: si la función devuelve una referencia, que sobrevive a la expresión completa, se hace una referencia colgante .
    Original:
    a temporary bound to a reference parameter in a function call exists until the end of the full expression containing that function call: if the function returns a reference, which outlives the full expression, it becomes a dangling reference.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • un temporal vinculado a una referencia en el inicializador utilizado en una nueva-expresión existe hasta el final de la expresión completa que contiene esa nueva-expresión, no tan largo como el objeto inicializado. Si el objeto inicializado sobrevive a la plena expresión, su socio de referencia se convierte en una referencia colgando .
    Original:
    a temporary bound to a reference in the initializer used in a new-expression exists until the end of the full expression containing that new-expression, not as long as the initialized object. If the initialized object outlives the full expression, its reference member becomes a dangling reference.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
En general, el tiempo de vida de un temporal no puede ser ampliado por el "pasarlo": una segunda referencia, inicializado a partir de la referencia a que el temporal estaba obligado, no afecta a su vida .
Original:
In general, the lifetime of a temporary cannot be further extended by "passing it on": a second reference, initialized from the reference to which the temporary was bound, does not affect its lifetime.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Notas

Las referencias aparecen sin inicializadores sólo en función de la declaración de parámetros, en la declaración de tipo de función de retorno, en la declaración de un miembro de la clase, y con el especificador extern .
Original:
References appear without initializers only in function parameter declaration, in function return type declaration, in the declaration of a class member, and with the extern specifier.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Ejemplo

#include <utility>
#include <sstream>
struct S {
 int mi;
 const std::pair<int,int>& mp; // reference member
};
 
void foo(int) {}
 
struct A {};
struct B : A {
   int n;
   operator int&() { return n; };
};
 
B bar() {return B(); }
 
//int& bad_r; // error: no initializer
extern int& ext_r; // OK
 
int main()
{
 // lvalues
    int n = 1;
    int& r1 = n;  // lvalue reference to the object n
    const int& cr(n); // reference can be more cv-qualified
    volatile int& cv{n}; // any initializer syntax can be used
    int& r2 = r1; // another lvalue reference to the object n
//    int& bad = cr; // error: less cv-qualified
    int& r3 = const_cast<int&>(cr); // const_cast is needed
 
    void (&rf)(int) = foo; // lvalue reference to function
    int ar[3];
    int (&ra)[3] = ar; // lvalue reference to array
 
    B b;
    A& base_ref = b; // reference to base subobject
    int& converted_ref = b; // reference to the result of a conversion
 
// rvalues
//  int& bad = 1; // error: cannot bind lvalue ref to rvalue
    const int& cref = 1; // bound to rvalue
    int&& rref = 1; // bound to rvalue
 
    const A& cref2 = bar(); // reference to A subobject of B temporary
    A&& rref2 = bar();      // same
 
    int&& xref = static_cast<int&&>(n); // bind directly to n
//  int&& copy_ref = n; // error: can't bind to an lvalue
    double&& copy_ref = n; // bind to an rvalue temporary with value 1.0
 
// restrictions on temporary lifetimes
    std::ostream& buf_ref = std::ostringstream() << 'a'; // the ostringstream temporary
                      // was bound to the left operand of operator<<, but its lifetime
                      // ended at the semicolon: buf_ref is now a dangling reference.
 
    S a { 1, {2,3} }; // temporary pair {2,3} bound to the reference member
                      // a.mp and its lifetime is extended to match a
    S* p = new S{ 1, {2,3} }; // temporary pair {2,3} bound to the reference
                      // member a.mp, but its lifetime ended at the semicolon
                      //  p->mp is a dangling reference
    delete p;
}


[editar] Ver también