【发布时间】:2018-11-16 21:56:10
【问题描述】:
我正在 VC++ 上编写一个简单的 UTF8 到 WideStr 函数。
MtoW.h
#pragma once
#include <Windows.h>
#include <string>
using namespace std;
wstring UTF8toWide(const char*& in);
MtoW.cpp
#include "MtoW.h"
#include <string>
#include <cassert>
using namespace std;
wstring UTF8toWide(const char*& in) {
int size = MultiByteToWideChar(CP_UTF8, 0, in, -1, NULL, 0);
wchar_t* wide_str = new wchar_t[size];
int result_size = MultiByteToWideChar(CP_UTF8, 0, in, -1, wide_str, size);
assert(size == result_size);
return wstring(wide_str);
}
main.cpp
#include <string>
#include <iostream>
#include "MtoW.h"
using namespace std;
int main()
{
string s = "hi";
//s.c_str();
//const char* q = "abc";
//const char*& c = q;
wstring q = UTF8toWide(s.c_str()); //error
}
我收到 cannot convert from const char* to const char *& 错误,为什么?s.c_str() 是 const char* 类型,我的代码应该可以工作。
【问题讨论】:
-
看起来
UTF8toWide内存泄漏:wchar_t[]在哪里被删除了? -
@drRobertz :D 我忘记写了。谢谢提醒。
标签: c++ visual-c++ reference pass-by-reference