◐ Shell
clean mode source ↗

direct initialization - cppreference.com

De cppreference.com

<metanoindex/>

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.

Sintaxe

T object ( arg );

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

(1)
T object { arg };

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

(2) (desde C++11)
T ( other )

T ( arg1, arg2, ... );

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

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:

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.

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.

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';
}

Saída:

Veja também