【发布时间】:2012-03-13 20:06:13
【问题描述】:
我正在寻找一种使用 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
}
}
}
【问题讨论】:
-
在任何一种情况下,new 都会在分配失败时抛出异常,而不是返回 0。
-
对于大多数真正的Win32 API函数,在第一次调用之前需要将“size”初始化为0。
-
如果您需要在第二次调用之前对数组进行零初始化,那么
std::vector<char>会更好(因为它会自动且快速地执行此操作)。如果您不需要将数组归零,那么您所拥有的将优于std::vector<char>,因为它不会花费周期进行不需要的零初始化。而且,如果您不在需要最高性能的环境中,那么使用哪一种都没有关系。 -
别忘了
new char[size]()。
标签: c++ arrays memory-management c++11 unique-ptr