dic*_*ice 1 c++ arrays memory-management unique-ptr c++11
我正在寻找一种使用C++ 11中引入的新指针模板来管理数组范围的简洁方法,这里的典型场景是调用win32 api函数时.
我在这里发帖是因为虽然对更复杂的事情有很多讨论,但这个相对简单的场景似乎没有被讨论过,我想知道是否有比我现在开始做的更好的选择.
#include <memory>
void Win32ApiFunction(void* arr, int*size)
{
if(arr==NULL)
*size = 10;
else
{
memset(arr,'x',10);
((char*)arr)[9]='\0';
}
}
void main(void)
{
// common to old and new
int size;
Win32ApiFunction(NULL,&size);
// old style - till now I have done this for scope reasons
if(char* data = new char[size])
{
Win32ApiFunction(data,&size);
// other processing
delete [] data;
}
// new style - note additional braces to approximate
// the previous scope - is there a better equivalent to the above?
{
std::unique_ptr<char[]> data1(new char[size]);
if(data1)
{
Win32ApiFunction(data1.get(),&size);
// other processing
}
}
}
Run Code Online (Sandbox Code Playgroud)
Beg*_*oth 11
最干净的方法是使用std::vector,即使C++ 98保证它与C风格的数组兼容(即它存储为单个连续块),你只需要将指针传递给你的第一个元素Win32ApiFunction.
std::vector<char> data(size);
Win32ApiFunction(&data[0], &size);
Run Code Online (Sandbox Code Playgroud)
在C++ 11中有一个特殊的成员函数std::vector<T>::data(),它返回指向数组开头的指针(所以你不需要operator& ()为向量值类型和使用过载而烦恼std::addressof,参见如何在操作符时可靠地获取对象的地址重载?对于C++ 98 operator&()重载问题).