Espaços nominais
Variantes
Acções

direct initialization

Da cppreference.com
< cpp‎ | language

 
 
Linguagem C + +
Tópicos gerais
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.
Controle de fluxo
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.
Declarações execução condicional
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.
Instruções de iteração
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 declarações
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.
Funções
Original:
Functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
declaração da função
lambda declaração da função
modelo de função
linha especificador
especificações de exceção (obsoleta)
noexcept especificador (C++11)
Exceções
Original:
Exceptions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Namespaces
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)
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
armazenamento duração especificadores
constexpr especificador (C++11)
auto especificador (C++11)
alignas especificador (C++11)
Inicialização
Original:
Initialization
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Literais
Original:
Literals
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Expressões
Original:
Expressions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
representações alternativas
Utilitários
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
tipo de alias declaração (C++11)
atributos (C++11)
Conversões
Original:
Casts
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
conversões implícitas
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
Elenco C-estilo e funcional
Alocação de memória
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.
Classes
Original:
Classes
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Classe propriedades específicas de função
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.
Funções membro especiais
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.
Modelos
Original:
Templates
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
modelo de classe
modelo de função
especialização de modelo
pacotes de parâmetros (C++11)
Diversos
Original:
Miscellaneous
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Assembly embutido
 
Inicializa um objeto do conjunto explícito de argumentos do construtor.
Original:
Initializes an object from explicit set of constructor arguments.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Índice

[editar] Sintaxe

T object ( arg );

T object ( arg1, arg2, ... );

(1)
T object { arg };

T object { arg1, arg2, ... };

(2) (a partir do C++ 11)
T ( other )

T ( arg1, arg2, ... );

(3)
static_cast< T >( other ) (4)
new T(args, ...) (5)
Class::Class() : member(args, ...) {... (6)
[arg](){... (7) (a partir do C++ 11)

[editar] Explicação

Inicialização direta é realizada nas seguintes situações:
Original:
Direct initialization is performed 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)
inicialização com uma lista não vazia de expressões entre parênteses
Original:
initialization with a nonempty parenthesized list of expressions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
2)
durante a seqüência lista de inicialização, se não constuctors inicializador-lista são fornecidos e um construtor de correspondência é acessível, e todas as conversões necessárias implícitas não são estreitamento.
Original:
during lista de inicialização sequence, if no initializer-list constuctors are provided and a matching constructor is accessible, and all necessary implicit conversions are non-narrowing.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
3)
inicialização de um prvalue temporária por elenco funcional ou com uma lista de expressões entre parênteses
Original:
initialization of a prvalue temporary by elenco funcional or with a parenthesized expression list
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
4)
inicialização de um prvalue temporário por expession static_cast
Original:
initialization of a prvalue temporary by a static_cast expession
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
5)
inicialização de um objeto com duração de armazenamento dinâmico por uma expressão de novo com um inicializador não vazio
Original:
initialization of an object with dynamic storage duration by a new-expression with a non-empty initializer
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
6)
inicialização de uma base ou um membro não-estático por lista de inicializador construtor
Original:
initialization of a base or a non-static member by constructor lista de inicializador
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
7)
inicialização de membros de fecho objeto das variáveis ​​capturadas por cópia em uma expressão lambda
Original:
initialization of closure object members from the variables caught by copy in a lambda-expression
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Os efeitos da inicialização direta são:
Original:
The effects of direct initialization are:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • Se T é um tipo de classe, os construtores de T são examinados ea melhor combinação é selecionada por resolução de sobrecarga. O construtor é então chamado para inicializar o objeto.
    Original:
    If T is a class type, the constructors of T are examined and the best match is selected by overload resolution. The constructor is then called to initialize the object.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Caso contrário, se T é um tipo não-classe, conversões standard são utilizadas, se necessário, para converter o valor de other à versão não qualificado de cv-T.
    Original:
    Otherwise, if T is a non-class type, conversões standard are used, if necessary, to convert the value of other to the cv-unqualified version of T.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

[editar] Notas

Inicialização direta é mais permissiva do que copiar-inicialização: cópia de inicialização somente considera não-explícitas construtores e funções definidas pelo usuário de conversão, enquanto a inicialização direta considera todos os construtores e seqüências de conversão implícitos.
Original:
Direct-initialization is more permissive than copy-initialization: copy-initialization only considers non-explicit constructors and user-defined conversion functions, while direct-initialization considers all constructors and implicit conversion sequences.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Exemplo

#include <string>
#include <iostream>
#include <memory>
 
struct Foo {
    int mem;
    explicit Foo(int n) : mem(n) {}
};
 
int main()
{
    std::string s1("test"); // constructor from const char*
    std::string s2(10, 'a');
 
    std::unique_ptr<int> p(new int(1)); // OK: explicit constructors allowed
//  std::unique_ptr<int> p = new int(1); // error: constructor is explicit
 
    Foo f(2); // f is direct-initialized:
              // constructor parameter n is copy-initialized from the rvalue 2
              // f.mem is direct-initialized from the parameter n
//  Foo f2 = 2; // error: constructor is explicit
 
    std::cout << s1 << ' ' << s2 << ' ' << *p << ' ' << f.mem  << '\n';
}

Output:

test aaaaaaaaaa 1 2

[editar] Veja também