我有一个我自己的不可变wstring实现,但实际使用它时遇到问题。当我需要wchar数组时,我需要它以null结尾,所以我这样做:
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&lt;&gt;在函数结束时死掉,所以我得到一个空的wchar *。另外,因为Auto&lt;&gt;有一个析构函数,这个方法永远不会被内联。所以我的方向完全错误。我试着查看std :: wstring源代码,但是对于所有内部typedef来说它是不可读的,我注意到它不仅仅是存储了一些东西比如我的wchar *数据,还有一个wchar *,我假设它是jut 1个字符(空终止符):
_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在被返回之前在哪里被终止?或者他们只是把它扔出原始状态?
答案 0 :(得分:2)
您可以在data
数组中存储以null结尾的字符串,然后将其作为const wchar *
返回。它将消除不必要的数据复制。
编辑:
关于你提到的wstring源中的额外wchar指针。它可能是end()指针。实现分配一些数据缓冲区来存储字符串,但是分配的缓冲区比字符串大,所以它将指针存储到缓冲区的开头(数据)和指向数据末尾的指针(到{{1 wchar)。这样,'\0'
函数可以轻松实现为size()
,即使wstring本身包含int size() const{ return end_ptr-data; }
也可以正常工作。
答案 1 :(得分:1)
_Myptr以null结尾,因此当c_str返回_Myptr时无需添加终止符。