如果将键定义为std :: string,则存储在REDIS中的POD结构的验证将失败
deserialization of pod struct stored in redis fails if key is defined as std::string
pod struct在redis中的存储与 const char *
一起工作,但如果涉及 std::string
,则不行。
const char *示例
#include <hiredis/hiredis.h>
#include <string.h>
#include <string>
#include <iostream>
using namespace std;
struct Test
{
const uint32_t id;
const char *name;
};
int main() {
redisContext *context = redisConnect("127.0.0.1", 6379);
if (context == NULL || context->err) {
if (context) {
printf("Error: %sn", context->errstr);
} else {
printf("Can't allocate redis contextn");
}
exit(EXIT_FAILURE);
}
Test obj = {(uint32_t) 123, "foo bar"};
const size_t size = 2 * sizeof(uint32_t) + (strlen(obj.name) + 1);
cout << "object{id: " << obj.id << ", name:' " << obj.name << "'}; size: " << size << endl;
redisReply *reply = 0;
const char *key = strdup("some-key");
reply = (redisReply *) redisCommand(context, "SET %b %b", key, strlen(key), &obj, size);
if (!reply)
return REDIS_ERR;
freeReplyObject(reply);
reply = (redisReply *) redisCommand(context, "GET %s", key);
if (!reply)
return REDIS_ERR;
Test *res = (struct Test*) reply->str;
cout << "result{id: " << res->id << ", name:' " << res->name << "'}; size: " << size << endl;
freeReplyObject(reply);
redisFree(context);
}
如果我更换行:
const char *key = strdup("some-key");
reply = (redisReply *) redisCommand(context, "SET %b %b", key, strlen(key), &obj, size);
std::string key("some-key");
reply = (redisReply *) redisCommand(context, "SET %b %b", key.c_str(), key.size(), &obj, size);
执行始终以分段故障结束。
我无法自己解决这个问题,我真的很感谢任何帮助。
好吧,我明白了:更换第二个redisCommand
语句
reply = (redisReply *) redisCommand(context, "GET %b", key.c_str(), key.size());
解决了问题。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 如何在 malloc 内存中初始化非 POD 数据
- 使用 std::index_sequence 初始化具有固定大小数组成员的 POD 结构容器
- Qt5 远程对象 + 自定义类型,但不在 POD 中
- 带有 char[] 字段的 POD 结构的 constexpr 构造
- 如何使用 redis-plus-plus 存储二进制数据,就像我想存储结构一样?@for_stack?
- 非 POD 的零初始化
- C++定义构造函数使对象成为非 POD
- 是否可以使用 std::array 作为 POD 结构的数据容器?
- 指向 POD 类型的指针之间的静态转换与重新解释转换
- 具有非 POD 对象的 GLib 异步队列
- 约束类模板函数以接受特定的 POD 类型
- 从基本类型转换为非 POD 结构
- 我可以说服自动生成的构造函数将我的 POD 类成员归零吗?
- 根据 MSVC,具有易失性成员的结构不再是 POD
- 快速将无符号字符的向量强制转换为POD结构的向量,反之亦然
- POD类型是否完全等同于琐碎的标准布局类型
- 如何创建非 POD 类型的连续内存池?
- 使用 redis 进行日志缓存:是否可以创建逐出到 PostgreSQL 的逐出策略?
- 如果将键定义为std :: string,则存储在REDIS中的POD结构的验证将失败