简体   繁体   English

为什么std :: chrono :: time_point的行为不符合预期?

[英]Why does std::chrono::time_point not behave as expected?

#include <chrono>

int main()
{
    using clock = std::chrono::system_clock;
    using time_point = std::chrono::time_point<clock>;

    auto tp_now = clock::now();
    auto tp_min = time_point::min();

    bool b1 = tp_now > tp_min;
    bool b2 = (tp_now - tp_min) > std::chrono::seconds{ 0 };
    cout << boolalpha << b1 << endl << b2 << endl;
}

The expected output is: 预期的输出是:

true 真正

true 真正

But the actual output is: 但是实际输出是:

true 真正

false

Why does std::chrono::time_point not behave as expected? 为什么std::chrono::time_point行为不符合预期?

With: 带有:

using clock = std::chrono::system_clock;
using time_point = std::chrono::time_point<clock>;

time_point is implemented as if it stores a value of type Duration indicating the time interval from the start of the Clock's epoch. 实现time_point就好像它存储了一个类型为Duration的值,该值指示从时钟纪元开始的时间间隔。 (See std::chrono::time_point ) (请参阅std::chrono::time_point

The duration member type of clock (and of time_point ) is capable of representing negative durations. clock (和time_point )的duration成员类型能够表示负的持续时间。

Thus duration in your implementation may be implemented with a back-end signed integer, (it can be implemented with unsigned integer but with a complicated comparison). 因此,实现的duration可以使用后端有符号整数来实现(可以使用无符号整数来实现,但是需要进行复杂的比较)。

In that particular implementation, 在该特定实施中,

time_point::min();
time_point t(clock::duration::min());
time_point t(clock::duration(std::numeric_limits<Rep>::lowest()));

and tp_now is greater than zero , thus when you subtract them, you get an integer overflow because the result is larger than std::numeric_limits<Rep>::max() . 并且tp_now大于zero ,因此,当它们相减时,会得到整数溢出,因为结果大于std::numeric_limits<Rep>::max() In implementation with signed back-end, it's undefined behavior, in implementation with unsigned back-end, I don't know about it, but I guess its special comparison will make its false . 在带签名后端的实现中,它是未定义的行为,在带签名后端的实现中,我对此一无所知,但是我猜想它的特殊比较将使其为false

In this example , tp_min is -9223372036854775808 ticks from its epoch, that number is the same with std::numeric_limits<duration::rep>::lowest() 此示例中tp_min从其纪元tp_min-9223372036854775808滴答,该数字与std::numeric_limits<duration::rep>::lowest()


TL;DR; TL; DR; It's integer overflow. 这是整数溢出。 Don't use 不要使用

(tp1 - tp2) > std::chrono::duration<whatever_rep>::zero

Instead, use 相反,使用

tp1 > tp2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM