Вопрос

I am looking for a clean way to manage scope of arrays using the new pointer templates introduced in C++11, the typical scenario here is when calling into win32 api functions.

I am posting here because though there is plenty of discussion on more complex matters this relatively simple scenario doesn't seem to have been discussed and I'm wondering if there are better options than what I am now starting to do.

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

Нет правильного решения

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top