gpt4 book ai didi

c++ - 避免到处都有静态常量变量

转载 作者:行者123 更新时间:2023-11-28 02:08:10 24 4
gpt4 key购买 nike

我在 C++ 类的 C 包装器中有以下代码。我需要从我的 json::value 对象返回响应的字符串值。问题是,使用 c_str() 返回一个指针,该指针在函数末尾被销毁。因此,我有以下可怕且不安全的代码:-

const char* const response_Json(CResponse *resp) {
using namespace myclient;
Response *t = (Response*)resp;
const web::json::value& json = t->Json(); // NOTE: Json() can ONLY be called ONCE
std::ostringstream stream;
stream << json; // REQUIRED to get raw JSON as text, as serialize(void) does NOT work
//t->Json().serialize(stream); // Doesn't work - blank result
std::string asstr = stream.str();
static const std::string& statref = stream.str(); // REQUIRED to ensure reference to string, and thus contained c_str, is not destroyed
static const char* pref = statref.c_str(); // REQUIRED so we have a local char pointer that is not temporary, and thus destroyed at function's exit

return pref;
}

我发现 statref 和 pref 都需要被声明为 static const 以便实际返回一个值而不是一个悬挂指针(即 statref 和 pref 需要整个对象图到 asstr)但是我'我不确定为什么。我原以为 pref 的那个就足够了。

我想删除所有静态变量,因为这个函数将被多次调用,而且可能是并行调用。

我需要做的是返回避免使用静态常量的 C char* 或其拷贝。我已经搜索了好几天,但在任何地方都找不到答案。

我得出的结论是,我需要传入此函数修改的 char*,而不是返回。

最佳答案

您需要将缓冲区传递给 response_Json 函数,该函数应将字符串复制到调用方提供的缓冲区中。

基本上你需要这个:

void const response_Json(CResponse *resp, char *buffer) {
using namespace myclient;
Response *t = (Response*)resp;
const web::json::value& json = t->Json(); // NOTE: Json() can ONLY be called ONCE
std::ostringstream stream;
stream << json; // REQUIRED to get raw JSON as text, as serialize(void) does NOT work
//t->Json().serialize(stream); // Doesn't work - blank result
std::string asstr = stream.str();
strcpy(buffer, asstr.c_str);
}

为了简单起见,这里没有进行缓冲区溢出检查。

可能在函数的json stuff部分还有改进的余地

关于c++ - 避免到处都有静态常量变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36713513/

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