1

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

1 に答える 1

11

最もクリーンな方法は使用することstd::vectorです。C++98でもCスタイルの配列との互換性が保証されます(つまり、単一の連続ブロックとして格納されます)。必要なのは、最初の要素へのポインターをに渡すことだけですWin32ApiFunction

std::vector<char> data(size);
Win32ApiFunction(&data[0], &size);

C ++ 11には、配列の先頭へのポインターを返す特別なメンバー関数があります(したがって、ベクトル値型のstd::vector<T>::data()オーバーロードや使用について気にする必要はありません。演算子の場合にオブジェクトのアドレスを確実に取得するにはどうすればよいですか?」を参照してください。オーバーロードされていますか?オーバーロードに関するC ++ 98の問題の場合)。operator& ()std::addressofoperator&()

于 2012-02-23T12:08:39.067 に答える