Espaços nominais
Variantes
Acções

value 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)
Lança
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
 
Fornece o valor inicial padrão para um novo objeto.
Original:
Provides the default initial value to a new object.
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 {}; (1) (a partir do C++ 11)
T();

T{};

(2)
(a partir do C++ 11)
new T ();

new T {};

(3)
(a partir do C++ 11)

[editar] Explicação

Inicialização valor é realizada em três situações:
Original:
Value initialization is performed in three situations:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
1)
quando uma variável chamada (automático, estático ou segmento local) é declarada com o inicializador composto por um par de chaves. (a partir do C++ 11)
Original:
when a named variable (automatic, static, or thread-local) is declared with the initializer consisting of a pair of braces. (a partir do 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)
quando um objeto sem nome temporário é criado com o inicializador composto por um par de parênteses vazios ou chaves.
Original:
when a nameless temporary object is created with the initializer consisting of an empty pair of parentheses or braces.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
3)
quando um objecto com uma duração de armazenamento dinâmico é criado por uma expressão de novo com o inicializador constituído por um par de parênteses vazios ou chaves.
Original:
when an object with dynamic storage duration is created by a new-expression with the initializer consisting of an empty pair of parentheses or braces.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Os efeitos do valor de inicialização são:
Original:
The effects of value 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 com pelo menos um construtor fornecidos pelo utilizador de qualquer espécie, a construtor padrão é chamado.
    Original:
    If T is a class type with at least one user-provided constructor of any kind, the construtor padrão is called.
    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 não-união sem construtores fornecidos pelo usuário, em seguida, o objeto é inicializado com zero e depois o construtor padrão implicitamente declarado é chamado (a menos que seja trivial)
    Original:
    If T is an non-union class type without any user-provided constructors, then the object is inicializado com zero and then the implicitly-declared default constructor is called (unless it's trivial)
    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 matriz, cada elemento da matriz é de valor inicializado
    Original:
    If T is an array type, each element of the array is value-initialized
    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, o objeto é inicializado com zero.
    Original:
    Otherwise, the object is zero-initialized.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

[editar] Notas

O T object(); sintaxe não inicializar um objeto, que declara uma função que não tem argumento e T retornos. A forma de valor-inicializar uma variável chamada antes de C + 11 foi T object = T();, que inicializa um valor temporário e então cópia inicializa o objeto:.. a maioria dos compiladores otimizar a cópia neste caso
Original:
The syntax T object(); does not initialize an object; it declares a function that takes no arguments and returns T. The way to value-initialize a named variable before C++11 was T object = T();, which value-initializes a temporary and then copy-initializes the object: most compilers optimize out the copy in this case.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Referências não pode ter um valor inicializado.
Original:
References cannot be value-initialized.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Todos os contêineres padrão (std::vector, std::list, etc) valor inicializar seus elementos, quando construído com um argumento size_type única ou quando cultivadas por uma chamada para resize().
Original:
All standard containers (std::vector, std::list, etc) value-initialize their elements when constructed with a single size_type argument or when grown by a call to resize().
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 <vector>
#include <iostream>
 
struct T1 {
    int mem1;
    std::string mem2;
}; // no constructors
struct T2 { 
    int mem1;
    std::string mem2;
    T2(const T2&) {} // a constructor, but no default
};
struct T3 { 
    int mem1;
    std::string mem2;
    T3() {} // user-provided default ctor
};
 
std::string s{}; // calls default ctor, the value is "" (empty string)
int main()
{
    int n{};     // non-class value-initialization, value is 0
    double f = double(); // non-class value-init, value is 0.0
    int* a = new int[10](); // array of 10 zeroes
 
    T1 t1{}; // no ctors: zero-initialized
             // t1.mem1 is zero-initialized
             // t1.mem2 is default-initialized
//    T2 t2{}; // error: has a ctor, but no default ctor
    T3 t3{}; // user-defined default ctor:
             // t3.mem1 is default-initialized (the value is indeterminate)
             // t3.mem2 is default-initialized
 
    std::vector<int> v(3); // value-initializes three ints
 
    std::cout << s.size() << ' ' << n << ' ' << f << ' ' << a[9] << ' ' << v[2] << '\n';
    std::cout << t1.mem1 << ' ' << t3.mem1 << '\n';
    delete[] a;
}

Output:

0 0 0 0 0
0 4199376

[editar] Veja também