gpt4 book ai didi

c++ - 是 std::chrono::duration 默认初始化为 0

转载 作者:行者123 更新时间:2023-12-01 14:20:23 31 4
gpt4 key购买 nike

下面的 d 值是已初始化(大概为 0)还是未初始化(读取不安全)?

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

Documentation说默认构造函数是默认的。

下面的 std 库代码似乎表明它是未初始化的,因为最终 int64_t 是一个标量,而标量的默认初始化是没有初始化。

我的理解正确吗?令我惊讶的是 std::chrono::system_clock::time_point初始化为 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;

...

最佳答案

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;



这些一起说 duration默认初始化为 Rep默认初始化

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.



因此:
seconds s;  // no initialization.

然而,这:
seconds s{};  // zero-initialize

进行值初始化,对于标量是零初始化。

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


所以 duration客户可以选择未初始化或零初始化,标准提供 duration s 保证具有带符号的积分 Rep .如果您使用具有类类型的自定义持续时间 Rep , 那么它将由 Rep 的任何定义默认初始化如下。

关于c++ - 是 std::chrono::duration 默认初始化为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60686419/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com