【发布时间】:2014-04-13 01:04:48
【问题描述】:
持久化 std::chrono time_point 实例,然后将它们读回另一个相同类型的实例的正确方法是什么?
typedef std::chrono::time_point<std::chrono::high_resolution_clock> time_point_t;
time_point_t tp = std::chrono::high_resolution_clock::now();
serializer.write(tp);
.
.
.
time_point_t another_tp;
serializer.read(another_tp);
对写入/读取的调用,假设类型为 time_point_t 的实例可以以某种方式转换为字节表示,然后可以从磁盘或套接字等写入或读取。
Alf 建议的可能解决方案如下:
std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();
//Generate POD to write to disk
unsigned long long ns0 = t0.time_since_epoch().count();
//Read POD from disk and attempt to instantiate time_point
std::chrono::high_resolution_clock::duration d(ns0)
std::chrono::high_resolution_clock::time_point t1(d);
unsigned long long ns1 = t1.time_since_epoch().count();
if ((t0 != t1) || (ns0 != ns1))
{
std::cout << "Error time points don't match!\n";
}
注意:上面的代码有一个bug,因为最终实例化的时间点与原来的不匹配。
在旧样式 time_t 的情况下,通常只是根据其 sizeof 将整个实体写入磁盘,然后以相同的方式将其读回 - 简而言之,与新的 std::chrono 类型等效的是什么?
【问题讨论】:
标签: c++ serialization c++11 persistence chrono