Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is std::chrono::duration default initialized to 0

Tags:

Is the d value below initialized (to 0 presumably) or uninitialized (unsafe to read)?

std::chrono::system_clock::duration d;

Documentation says default constructor is defaulted.

std library code below seems to suggest it is uninitialized as ultimately int64_t is a scalar, and scalar's default initialization is no initialization.

Is my understanding correct? It surprised me sightly as std::chrono::system_clock::time_point is initialized to 0.

    struct system_clock
    {
      typedef chrono::nanoseconds                   duration;
...
    /// nanoseconds
    typedef duration<int64_t, nano>         nanoseconds;

...
    template<typename _Rep, typename _Period>
      struct duration
      {
    typedef _Rep                        rep;
    typedef _Period                     period;

...
like image 581
bill Avatar asked Mar 14 '20 19:03

bill


1 Answers

http://eel.is/c++draft/time.duration#2

Rep shall be an arithmetic type or a class emulating an arithmetic type.

http://eel.is/c++draft/time.duration#1

constexpr duration() = default;

Together these say that duration is default-initialized as Rep is default-initialized

http://eel.is/c++draft/dcl.init#7

To default-initialize an object of type T means:

  • If T is a (possibly cv-qualified) class type ([class]), constructors are considered. The applicable constructors are enumerated ([over.match.ctor]), and the best one for the initializer () is chosen through overload resolution ([over.match]). The constructor thus selected is called, with an empty argument list, to initialize the object. (7.2)

  • If T is an array type, each element is default-initialized.

  • Otherwise, no initialization is performed.

Thus:

seconds s;  // no initialization.

However, this:

seconds s{};  // zero-initialize

does value initialization, which for scalars is zero-initialization.

http://eel.is/c++draft/dcl.init#list-3.11

Otherwise, if the initializer list has no elements, the object is value-initialized.

http://eel.is/c++draft/dcl.init#8

To value-initialize an object of type T means:

  • if T is a (possibly cv-qualified) class type ([class]), then ...
  • otherwise, the object is zero-initialized.

http://eel.is/c++draft/dcl.init#6

To zero-initialize an object or reference of type T means:

  • if T is a scalar type, the object is initialized to the value obtained by converting the integer literal 0 (zero) to T;90

So duration clients have their choice of either uninitialized or zero-initialized, with the std-supplied durations which are guaranteed to have a signed integral Rep. If you use a custom duration with a class type Rep, then it will be default-initialized by whatever definition that Rep follows.

like image 169
Howard Hinnant Avatar answered Sep 30 '22 19:09

Howard Hinnant