我有一个关于如何在不使用 STL 的情况下在 C++ 中使用持久性的问题。我想在内存中存储一些计算历史,并在调用程序时用新的计算更新它。我不能使用静态存储类,因为执行后,内存会丢失。
任何指针都会有所帮助。流媒体是正确的方法吗?
我有一个关于如何在不使用 STL 的情况下在 C++ 中使用持久性的问题。我想在内存中存储一些计算历史,并在调用程序时用新的计算更新它。我不能使用静态存储类,因为执行后,内存会丢失。
任何指针都会有所帮助。流媒体是正确的方法吗?
最简单的事情是在磁盘上写入和读取结构。首先,定义要存储的内容:
struct SavedState {
int32_t a;
float b;
char c[100]; // n.b. you cannot use std::string here!
} __attribute__((__packed__));
static_assert(std::is_trivially_copyable<SavedState>::value,
"SavedState must be trivially copyable");
然后,创建一些状态并保存它:
SavedState s = { 1, 2.3 };
snprintf(s.c, sizeof(s.c), "hello world!");
std::ofstream outfile("saved.state", std::ios::binary);
outfile.write(reinterpret_cast<char*>(&s), sizeof(s));
if (!outfile)
std::runtime_error("failed to write");
然后,恢复它:
SavedState t;
std::ifstream infile("saved.state", std::ios::binary);
infile.read(reinterpret_cast<char*>(&t), sizeof(t));
if (!infile)
throw std::runtime_error("failed to read");
一些重要的注意事项:
std::ios::binary
需要防止流“规范化”换行符(您存储的是二进制数据,而不是文本)。__packed__
需要确保结构在所有系统上具有相同的大小。同上int32_t
,而不仅仅是int
.static_assert
; 在早期版本的 C++ 中,您可以BOOST_STATIC_ASSERT
根据需要使用。