mardi 16 mai 2023

why vector

From CppReference Value initialization:

This is the initialization performed when an object is constructed with an empty initializer.

Syntax

(1)   T ()
(2)   new T ()
(3)   Class::Class(...) : member () { ... }
(4)   T object {}; (since C++11)
(5)   T {} (since C++11)
(6)   new T {} (since C++11)
(7)   Class::Class(...) : member {} { ... } (since C++11)

Explanation

Value initialization is performed in these situations:

  • (1), (5) when a nameless temporary object is created with the initializer consisting of an empty pair of parentheses or braces (since C++11);
  • (2), (6) 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 (since C++11);
  • (3), (7) when a non-static data member or a base class is initialized using a member initializer with an empty pair of parentheses or braces (since C++11);
  • (4) (since C++11) when a named object (automatic, static, or thread-local) is declared with the initializer consisting of a pair of braces.

This is fine as vector<T> v{}; seems has syntax (4).

Then it says

The effects of value initialization are:

    1. if T is a class type with no default constructor or with a user-declared (until C++11)user-provided or deleted (since C++11) default constructor, the object is default-initialized;
    1. if T is a class type with a default constructor that is not user-declared (until C++11)neither user-provided nor deleted (since C++11) (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and the semantic constraints for default-initialization are checked, and if T has a non-trivial default constructor, the object is default-initialized;
    1. if T is an array type, each element of the array is value-initialized;
    1. otherwise, the object is zero-initialized.

I assume this falls into case 2 as vector<T> has a default constructor that takes 0 parameter. Then this 'vector v' shall be zero-initialized, instead of default-initialized?

Aucun commentaire:

Enregistrer un commentaire