【问题标题】:WString implementation - returning null-terminated, am I going the correct way at all?WString 实现 - 返回空终止,我是否走正确的路?
【发布时间】: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 终止?或者他们只是将其以原始状态丢弃?

【问题讨论】:

    标签: c++ algorithm wstring


    【解决方案1】:

    您可以在data 数组中存储以空字符结尾的字符串,然后将其返回为const wchar *。它将消除不必要的数据复制。

    编辑:

    关于您提到的 wstring 源中的额外 wchar 指针。它可能是 end() 指针。该实现分配了一些数据缓冲区来存储字符串,但分配的缓冲区比字符串大,因此它存储指向缓冲区开头的指针(数据)和指向数据结尾的指针(指向'\0' wchar) 。这样size() 函数可以很容易地实现为int size() const{ return end_ptr-data; } 并且即使wstring 本身包含\0 也可以工作。

    【讨论】:

    • 这就是 wstring 的工作方式。如果需要,用户可以拨打wcsdup()创建副本。
    【解决方案2】:

    _Myptr 为空终止符,所以 c_str 返回 _Myptr 时无需添加终止符。

    【讨论】:

    • 但是它什么时候会被空终止?它不会在调用 c_str 时,所以它必须在其他地方
    • 通常在存储字符串时完成。所以例如当您使用 L"abc" 初始化 wstring 时,构造函数将 _Myptr 设置为 4 个字符的长缓冲区,复制 3 个字符并将第四个字符设置为零。 (实际上它可能更复杂)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-05
    • 2013-03-27
    • 1970-01-01
    相关资源
    最近更新 更多