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_ptr
to 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::move
the unique_ptr
. It looks like it unique_ptr
can only be moved to another unique_ptr
instead of a raw pointer.
Is it possible to transfer ownership from unique_ptr
to raw pointer
? Or just unique_ptr
not suitable for this case?
bool PreProcess(int* v) { }
bool GetBuffer(int** ppRetBuf, int size)
{
std::unique_ptr<int[]> buf(new (std::nothrow) int[size]());
if(PreProcess(buf.get())
{
*ppRetBuf = std::move(buf);
return true;
}
return false;
}
int main()
{
int * buf = nullptr;
GetBuffer(&buf, 100);
}
source
share