为什么 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;
}
预期输出为:
true
true
但实际输出是:
true
false
为什么 std::chrono::time_point
没有按预期运行?
有:
using clock = std::chrono::system_clock;
using time_point = std::chrono::time_point<clock>;
time_point
的实现就好像它存储了一个 Duration 类型的值,指示从时钟纪元开始的时间间隔。 (参见 std::chrono::time_point
)
clock
(和 time_point
)的 duration
成员类型能够表示负持续时间。
因此duration
在你的实现中可以用后端有符号整数来实现,(可以用无符号整数来实现,但是比较复杂)。
在那个特定的实现中,
time_point::min();
time_point t(clock::duration::min());
time_point t(clock::duration(std::numeric_limits<Rep>::lowest()));
和 tp_now
大于 zero
,因此当你减去它们时,你会得到整数溢出,因为结果大于 std::numeric_limits<Rep>::max()
。在带有签名后端的实现中,它是未定义的行为,在带有未签名后端的实现中,我不知道,但我猜它的特殊比较会使它 false
.
在this example中,tp_min
是-9223372036854775808
个时间点,这个数字与std::numeric_limits<duration::rep>::lowest()
相同
TL;DR;这是整数溢出。不要使用
(tp1 - tp2) > std::chrono::duration<whatever_rep>::zero
改为使用
tp1 > tp2
#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;
}
预期输出为:
true
true
但实际输出是:
true
false
为什么 std::chrono::time_point
没有按预期运行?
有:
using clock = std::chrono::system_clock;
using time_point = std::chrono::time_point<clock>;
time_point
的实现就好像它存储了一个 Duration 类型的值,指示从时钟纪元开始的时间间隔。 (参见 std::chrono::time_point
)
clock
(和 time_point
)的 duration
成员类型能够表示负持续时间。
因此duration
在你的实现中可以用后端有符号整数来实现,(可以用无符号整数来实现,但是比较复杂)。
在那个特定的实现中,
time_point::min();
time_point t(clock::duration::min());
time_point t(clock::duration(std::numeric_limits<Rep>::lowest()));
和 tp_now
大于 zero
,因此当你减去它们时,你会得到整数溢出,因为结果大于 std::numeric_limits<Rep>::max()
。在带有签名后端的实现中,它是未定义的行为,在带有未签名后端的实现中,我不知道,但我猜它的特殊比较会使它 false
.
在this example中,tp_min
是-9223372036854775808
个时间点,这个数字与std::numeric_limits<duration::rep>::lowest()
TL;DR;这是整数溢出。不要使用
(tp1 - tp2) > std::chrono::duration<whatever_rep>::zero
改为使用
tp1 > tp2