gpt4 book ai didi

c++ - 获取 std::wstring 的内部指针的地址是否安全?

转载 作者:行者123 更新时间:2023-11-27 23:33:29 26 4
gpt4 key购买 nike

我有一个像下面这样使用的接口(interface):

if (SUCCEEDED(pInterface->GetSize(&size))
{
wchar_t tmp = new wchar_t[size];
if (SUCCEEDED(pInterface->GetValue(tmp, size)))
{
std::wstring str = tmp;
// do some work which doesn't throw
}
delete[] tmp;
}

这样做安全且便携吗?

if (SUCCEEDED(pInterface->GetSize(&size))
{
std::wstring str;
str.resize(size-1);
if (SUCCEEDED(pInterface->GetValue(&str[0], size)))
{
// do some work
}
}

现在,显然这有效(不会崩溃/损坏内存),否则我不会问,但我主要想知道是否有令人信服的理由不这样做。

编辑: 实际上,我已将其更改为 .resize(size-1),因为显然已为您考虑了空字符(无论如何在 VS 2010 之前)。使用 .resize(size) 结束了附加到字符串末尾的位置导致:

str.resize(size);
pInterface->GetValue(&str[0], size);
str contains L"foo\0";
str += L"bar";
str contains L"foo\0bar";

由于中间的空值,尝试使用生成的 str.c_str 最终看起来像 L"foo"。

最佳答案

正如 AraK 指出的那样,字符串存储可能不连续,尽管这不太可能。您还可以考虑使用 vector :

if (SUCCEEDED(pInterface->GetSize(&size))
{
std::vector <wchar_t> vtmp( size );
if (SUCCEEDED(pInterface->GetValue( & vtmp[0], size)))
{
std::wstring str = & vtmp[0];
// or maybe don't bother with the string - just use the vector
}
}

哪个更有可能是异常安全的。

关于c++ - 获取 std::wstring 的内部指针的地址是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3029964/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com