【问题标题】:Content of wchar is deletedwchar 的内容被删除
【发布时间】:2015-10-15 18:17:54
【问题描述】:

我有这个代码:

JSONObject object;
if (value->IsObject())
{
    object = value->AsObject();
    const wchar_t *tmp = from_string(entity_id);
    std::wcout << tmp << std::endl;
    std::wcout.flush();
    if (object.find(tmp) != object.end())
    {
        std::wcout << tmp << std::endl;
        std::wcout.flush();
        initFromJSON(object[tmp]->AsObject());
    }
    else
    {
        return false;
    }

}

这里的问题是,inner if 语句后,tmp 的内容为空。在此之前不是。 当我尝试调试时,一切正常,内容没有被删除。但是当我运行程序时,内容被删除。知道为什么吗?

方法 from_string(entity_id) 只能像这样从字符串转换为 wchar:

std::wstring result;
for (int i = 0; i<content.length(); i++)
    result += wchar_t(content[i]);
return result.c_str();

方法JSONObject::find(...)JSONObject::end()是这样的:

iterator find(const key_type& __k)             {return __tree_.find(__k);}
iterator end() _NOEXCEPT {return __tree_.end();}

我不认为这是 find(...) 或 end() 中的问题。我猜这个问题出在其他地方,但我找不到它。因为在if语句之后wchar的内容是空的我不能说

initFromJSON(object[tmp]->AsObject());

因为object[tmp] 不存在。

任何建议我做错了什么?

【问题讨论】:

  • 顺便说一句,我很确定您不需要调用 std::wcout.flush ,因为您使用了 std::endl 来刷新该流的缓冲区。
  • 按照 sam redway 的建议检查冲洗
  • 即使我删除std::wcout.flush 错误仍然发生
  • 您的from_string 函数在离开作用域时会破坏std::wstring,因此来自c_str 的指针不再有效。
  • @Youka,但是为什么首先 std::wcout 打印变量 tmp 的正确内容

标签: c++ c++11 wchar-t


【解决方案1】:

问题是您的from_string 函数返回一个指向本地实体的指针,即std::wstring::c_str() 的返回值。因此,您引入了未定义的行为。

我完全看不出tmp 变量是指针的原因。你应该可以这样做:

std::wstring from_entity(...)
{
    std::wstring result;
    for (int i = 0; i<content.length(); i++)
        result += wchar_t(content[i]);
    return result;
}

然后是这个:

JSONObject object;
if (value->IsObject())
{
    object = value->AsObject();
    std::wstring tmp = from_string(entity_id);
    std::wcout << tmp << std::endl;
    std::wcout.flush();
    if (object.find(tmp.c_str()) != object.end())
    {
        std::wcout << tmp << std::endl;
        std::wcout.flush();
        initFromJSON(object[tmp.c_str()]->AsObject());
    }
    else
    {
        return false;
    }
}

请注意,返回的是 std::wstring,而不是指针。然后在函数本身中,如果需要传递const wchar_t*,则使用c_str()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多