【问题标题】:C++, conversion from utility:string_t to std::string crashes on returnC ++,从实用程序:string_t 到 std::string 的转换在返回时崩溃
【发布时间】:2016-04-28 05:42:47
【问题描述】:

我正在使用 casablanca 库来序列化 json 值。

我尝试使用typedef std::wstring string_tthis to convert from wstring to string 转换为std::string。编译正常,但是程序在执行返回行时就崩溃了。

std::string getString()
{
    web::json::value cvalue;
    /* ----- code ----- */
    typedef std::wstring string_t;
    string_t outputString = cvalue.serialize();

    typedef std::codecvt_utf8<wchar_t> convert_type;
    std::wstring_convert<convert_type, wchar_t> converter;
    std::string converted_str = converter.to_bytes(outputString);

    return converted_str;
}

我不明白为什么会崩溃。下面是调用该函数的行。

std::string s = getString();

程序在名为 xdebug 的文件中的第 free(_Ptr) 行触发了一个断点。我真的不明白这里在说什么。希望这有助于您澄清事情。

template<class _Ty>
    void __CLRCALL_OR_CDECL _DebugHeapDelete(_Ty *_Ptr)
    {   // delete from the debug CRT heap even if operator delete exists
    if (_Ptr != 0)
        {   // worth deleting
        _Ptr->~_Ty();
        // delete as _NORMAL_BLOCK, not _CRT_BLOCK, since we might have
        // facets allocated by normal new.
        free(_Ptr);
        }
    }

谢谢!

【问题讨论】:

  • 您是否尝试单步执行代码以查看崩溃的位置?
  • @NathanOliver 嗨,我的编辑有帮助吗?它在返回线上崩溃。但我不知道这背后发生了什么。
  • 从该函数中取出 json 内容,然后硬编码一个字符串文字,可能是 L"abc123" 并将其分配给 outputString。函数会崩溃吗?
  • @PaulMcKenzie 我刚试过。它在同一个地方坠毁。
  • @XTT 忽略编译错误,但我只是在 Visual Studio 2015 中尝试了这段代码:ideone.com/1STzFR 并且程序正常工作。也许您应该确切地告诉我们您使用的是哪个版本的 Visual Studio?更好的是,创建一个全新的控制台项目,复制并粘贴您在链接中看到的确切代码,构建并运行。如果它运行,那么您的 json Visual Studio 项目有问题。也许是不匹配的运行时库或类似的东西......

标签: c++ json string type-conversion casablanca


【解决方案1】:

在 C++ REST SDK 中有一个函数可以将 utility::string_t 转换为 utf8 std::string: utility::conversions::to_utf8string

reference documentation

【讨论】:

    最近更新 更多