【发布时间】:2014-01-13 13:16:57
【问题描述】:
我自己有一个不可变的 wstring 实现,但是在实际使用它时遇到了问题。当我需要 wchar 数组时,我需要它以空值结尾,所以我这样做:
wchar* String::CStr() const
{
wchar* temp = new wchar[size + 1];
for(int i = 0; i < size; i++)
{
temp[i] = data[i];
}
temp[size] = L'\0';
return(temp);
}
Now this is good and all, but I have no way of releasing the newly created wchar array, so there's a memory leak each time CStr() is used.So instead I tried using an automatic pointer to fix it:
Auto<wchar> String::CStr() const
{
wchar* temp = new wchar[size + 1];
for(int i = 0; i < size; i++)
{
temp[i] = data[i];
}
temp[size] = L'\0';
return(Auto<wchar>(temp));
}
Auto 只是存储 wchar* 并在析构函数中删除它。当然它根本不起作用,因为 Auto 在函数结束时死了,所以我得到一个空的 wchar*。另外,因为 Auto 有一个析构函数,这个方法永远不会被内联。所以我的方向完全错误。我试着环顾 std::wstring 源代码,但是它对于所有内部类型定义都非常不可读,我注意到它不只是存储类似于我的 wchar* 数据的内容,但也存储我认为只是 1 个字符(空终止符)的 wchar*:
_Elem *_Myptr; // pointer to allocated string
_Elem _Nul; // nul terminator for unallocated string
但是它并没有在方法中使用_Nul,它只是返回_Myptr:
const _Elem *__CLR_OR_THIS_CALL c_str() const
{ // return NTBS
return (_Myptr != 0 ? _Myptr : &_Nul);
}
但是我没有看到 _Myptr 在返回之前在哪里被 null 终止?或者他们只是将其以原始状态丢弃?
【问题讨论】: