C++,从实用程序:string_t到标准::字符串的转换在返回时崩溃

C++, conversion from utility:string_t to std::string crashes on return

本文关键字:转换 字符串 标准 返回 崩溃 实用程序 string C++      更新时间:2023-10-16

我正在使用卡萨布兰卡库来序列化json值。

我尝试使用 typedef std::wstring string_t 转换为 std::string,这将从 wstring 转换为字符串。它编译得很好,但程序在执行返回行时崩溃。

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);
        }
    }

谢谢!

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

参考文档