#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?
With:
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. (Seestd::chrono::time_point
)The
duration
member type ofclock
(and oftime_point
) is capable of representing negative durations.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).In that particular implementation,
and
tp_now
is greater thanzero
, thus when you subtract them, you get an integer overflow because the result is larger thanstd::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 itsfalse
.In this example,
tp_min
is-9223372036854775808
ticks from its epoch, that number is the same withstd::numeric_limits<duration::rep>::lowest()
TL;DR; It's integer overflow. Don't use
Instead, use