wstring 和 wchar_t* 转换(处理const)

函数原型需要 wchar_t* 输入参数,而手边只有wstring类型,怎么转换?

 

void Process(const unsigned char* pSrcChars, int srcSize, wchar_t* pDestChars, int* destSize)
{
}

int _tmain(int argc, _TCHAR* argv[])
{
    std::wstring dest;
    const std::string src;
    int destSize = 0;
    int srcSize = (int) src.length();
    wchar_t dummy;

    // compute size
    Process((const unsigned char*) src.c_str(), srcSize, &dummy, &destSize);

    //option 1-bad
    dest.resize(destSize);
    Process((const unsigned char*) src.c_str(), srcSize, (wchar_t*)dest.c_str(), &destSize);

    //option 2-also bad
    dest.resize(destSize);
    Process((const unsigned char*) src.c_str(), srcSize, const_cast<wchar_t*>(dest.c_str()), &destSize);

    //option 3-good
    wchar_t* destChars = new wchar_t[destSize+1];
    destChars[destSize] = L'\0';
    Process((const unsigned char*) src.c_str(), srcSize, destChars, &destSize);

    dest = std::wstring(destChars);
    delete destChars;
    
    return 0;
}

 

三种方法都可以编译通过。

[option 1]

dest.c_str() 得到C风格的以null结尾的字符串形式,以const修饰。(wchar_t*)dest.c_str() 强制去掉const。首先(casted type)variable 是C风格的转换,在cpp源文件中最好使用C++风格的转换,即specific_cast<casted type>(variable),specific_cast就是static_cast, const_cast, reinterpret_cast等。

用g++编译,打开-Wcast-qual 开关,会有warning。

$g++ -Wcast-qual test.cpp

warning: cast from type 'const wchar_t*' to type 'wchar_t*' casts away qualifiers

-Wcast-align
Warn whenever a pointer is cast such that the required alignment of the target is increased. For example, warn if a char * is cast to an int * on machines where integers can only be accessed at two- or four-byte boundaries.

 

[option 2]

使用了C++风格的转换,用const_cast去掉了const属性。

option 1 和 option 2 都是不好的编码风格。尽量不要用。

[option 3]

推荐使用。先分配wchar_t*,使用,复制给wstring,清理动态分配内存。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值