In gcc 4.84 in file /usr/include/c++/4.8 we have
namespace std
{
typedef duration<int64_t, nano> nanoseconds;
Why is the representation type for nanosecond a signed integer type? Why isn't it unsigned? when can we have a duration object with a negative value ?
when can we have a duration object with a negative value ?
Any time you want to represent a negative duration!
e.g. "Ten seconds earlier" would be std::chrono::seconds(-10)
and if you add that to some time_point t
then you get a time_point
that is ten seconds before t
.
The standard says "A duration
type measures time between two points in time (time_points
)." It doesn't say that it can only measure time between non-decreasing time points. So that means it can be used to measure the time between t1
and t2
even if t2 < t1
. And to do that simply, you need a negative value.
If durations couldn't be signed then, to represent an offset that means "earlier" not "later", you'd have to use something like std::pair<bool, duration>
where the bool
says whether it's a positive or negative offset, and then you'd have to do:
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;
}
This is dumb. The language and the hardware already support this far more expressively and efficiently, by using signed integers.
If two objects a
and b
are defined such that a - b
is a duration, then it's desirable to have a - b = -(b - a)
.
To implement that anti-commutative property, the duration needs to be signed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With