How to move unique_ptr to the source pointer?

I have a function that is used to allocate a buffer with a given size. The buffer will pre-process / fill some data before returning. This preprocess can return false to represent this buffer, which is not being processed correctly. So I want to apply RAII in this buffer to avoid an early return without delete[].

Usually I use unique_ptrto help me automatically free the local selected object. In this case, I need to return this allocated object (owned unique_ptr) and transfer ownership to the caller . But the compiler complains that I cannot convert unique_ptr<T[]>to T*, and I am std::movethe unique_ptr. It looks like it unique_ptrcan only be moved to another unique_ptrinstead of a raw pointer.

Is it possible to transfer ownership from unique_ptrto raw pointer? Or just unique_ptrnot suitable for this case?

bool PreProcess(int* v) { /* return nothing wrong? true: false; */ }

bool GetBuffer(int** ppRetBuf, int size)
{
    std::unique_ptr<int[]> buf(new (std::nothrow) int[size]());
    if(PreProcess(buf.get())
    {
        *ppRetBuf = std::move(buf); // Compiler complains:  
                                    // Error C2440 '=': cannot convert from 'std::unique_ptr<int [],std::default_delete<_Ty>>' to 'int *'
        return true;
    }
    return false; // No need to manually delete[] failure buffer
}

int main()
{
    int * buf = nullptr;
    GetBuffer(&buf, 100);
}
+4
source share
2 answers

How to move unique_ptr to the source pointer?

, - unique_ptr .

std::unique_ptr::release(), unique_ptr . unique_ptr. , , , , . , .

, unique_ptr, -, .

+6

ppRetBuf buf - .

, , buf

*ppRetBuf = buf.release();
+5

Source: https://habr.com/ru/post/1612700/


All Articles