I have a variable called last_timestamp_ which is declared as follows:
using TimePoint = std::chrono::time_point<std::chrono::system_clock, std::chrono::duration<double>> TimePoint last_timestamp_
and I want to initialize it with zero, how do I do that? Thanks
using TimePoint = std::chrono::time_point<std::chrono::system_clock,
std::chrono::duration<double>>;
TimePoint last_timestamp_{};
It would actually work without the {} too, but imho it is better style to explicitly zero-initialize it.
You can read this two ways:
last_timestamp_ to 0.0s, or to its epoch.last_timestamp_ to 1970-01-01 00:00:00 UTC.The reason you can say the second part is because it is a de-facto standard that all implementations track Unix Time with system_clock in C++11/14/17. For C++20 this industry practice has been officially specified.
Important note: This specification is strictly for time_points based on system_clock. One can not assume this epoch for all chrono time_points.
Presuming from the comments that your use looks like:
while (...)
{
if (std::chrono::system_clock::now() > last_timestamp_ + threshold)
{
// now() - last_timestamp_ > threshold
...
last_timestamp_ = std::chrono::system_clock::now();
}
};
Your first iteration will be true assuming threshold isn't larger than 51 years.
Just to future-proof your code, it's worth a comment:
TimePoint last_timestamp_{}; // 1970-01-01
Now if you change clocks for any reason, you know that you may have to revisit this initial value. For example on some platforms the epoch of file_clock will be far in the future, breaking this code if it switched to file_clock. C++20 offers syntax to make this initialization more explicit:
using namespace std::chrono_literals;
TimePoint last_timestamp_ = std::chrono::sys_days{1970y/1/1};
Now the comment is unnecessary.
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