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
}
}
}