gpt4 book ai didi

c++ - 为什么 chrono::nanoseconds 的表示类型是有符号整数类型?

转载 作者:太空狗 更新时间:2023-10-29 23:25:20 24 4
gpt4 key购买 nike

在文件/usr/include/c++/4.8 中的 gcc 4.84 中我们有

namespace std  
{
typedef duration<int64_t, nano> nanoseconds;

为什么纳秒的表示类型是有符号整数类型?为什么不是未签名的?我们什么时候可以有一个负值的持续时间对象?

最佳答案

when can we have a duration object with a negative value ?

任何时候你想表示负持续时间!

例如“早十秒”将是 std::chrono::seconds(-10)如果你把它加到一些time_point t然后你得到一个time_point那是 t 前十秒.

标准说“duration 类型测量两个时间点 (time_points) 之间的时间。”它并没有说它只能测量非减少时间点之间的时间。所以这意味着它可以用来测量 t1 之间的时间。和 t2即使t2 < t1 .为了简单地做到这一点,您需要一个负值。

如果无法对持续时间进行签名,那么要表示表示“较早”而不是“较晚”的偏移量,您必须使用类似 std::pair<bool, duration> 的内容bool在哪里说明它是正偏移还是负偏移,然后您必须执行以下操作:

chrono::time_point adjust(chrono::time_point t, pair<bool, duration> offset)
{
if (offset.first) // positive
return t + offset.second;
else // negative
return t - offset.second;
}

这是愚蠢的。通过使用带符号的整数,语言和硬件已经更加表达和有效地支持这一点。

关于c++ - 为什么 chrono::nanoseconds 的表示类型是有符号整数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42246545/

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