wstring :: c_str()包含垃圾 [英] wstring::c_str() contains garbage

查看:638
本文介绍了wstring :: c_str()包含垃圾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个std::wstring decode(const char *s)函数.

我这样使用它:

const char *src = "some string";
const wchar_t *result = decode(src).c_str();

我总是在result[0]中得到垃圾,有时也在result[1]中得到垃圾.

I always get garbage in result[0], sometimes in result[1] too.

当我以其他方式使用它时,我不会得到垃圾:

I dont get garbage when I use it in another way:

std::wstring res = decode(src);
const wchar_t *result = res.c_str();

我的decode函数定义如下,它的工作.唯一的问题是调用代码(上面).

My decode function defined as below, and it does it's job. Only problem is calling code(above).

std::wstring decode(const char *s, UINT cp=CP_ACP)
{
    if(s == NULL)
        return std::wstring();
    int length = ::MultiByteToWideChar(cp, 0, s, -1, NULL, 0 );
    wchar_t *buf = new wchar_t[length];
    ::MultiByteToWideChar(cp, 0, s, -1, buf, length);
    std::wstring r(buf);
    delete[] buf;
    return r;
}

我使用Visual C ++ 2008 SP1进行编译.

I use Visual C++ 2008 SP1 to compile.

推荐答案

const wchar_t *result = decode(src).c_str();

decode的返回值是一个临时值,在调用c_str()后将销毁.因此,result指向释放的内存.

The return value of decode is a temporary value and is destroyed after the call to c_str(). Thus result points to freed memory.

所以

  • 延长返回值的寿命(例如,将其分配给局部变量)
  • 复制结果

这篇关于wstring :: c_str()包含垃圾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆