gpt4 book ai didi

c++ - 在结构中使用字符串时出现段错误

转载 作者:行者123 更新时间:2023-11-28 01:39:31 24 4
gpt4 key购买 nike

我数据库中的表有一个 blob 类型的列。我用它来存储以下结构:

struct a
{
int x;
string y;
} ;

我已经编写了一个 C++ 函数来使用上述结构的变量检索此 blob。我正在为此使用 cass_value_get_bytes 函数。

问题是如果我使用上面提到的结构,我会得到一个段错误。但是,如果我将字符串类型更改为字符数组,问题就解决了。我无法理解为什么我不能使用字符串变量,因为使用字符串比使用字符数组要简洁得多。

最佳答案

函数cass_value_get_string()cass_value_get_bytes()返回指向缓冲区的指针,其生命周期绑定(bind)到 CassResult .当结果被删除时,值的内存也会被删除。您需要将内存复制到字符串的缓冲区中。 cass_value_get_string()也可以用于 blob,它避免了必须执行 reinterpret_cast<> .您可以执行以下操作:

#include <cassandra.h>
#include <string>

std::string to_string(CassValue* value) {
const char* str;
size_t len;
cass_value_get_string(value, &str, &len);
return std::string(str, len);
}

struct SomeData {
int x;
std::string y;
};

int main() {
SomeData data;
CassValue* value = NULL; /* This needs to be set from the result */
data.y = to_string(value);
}

关于c++ - 在结构中使用字符串时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47833332/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com