A common pattern can be found in some Windows Win32 API calls,
in which the use of
std::unique_ptr can come in handy,
e.g. when you don't exactly know how big an output buffer should be
when calling some Win32 API (that will write some data inside that
// Buffer dynamically allocated by the caller, and filled by some Win32 API function.
// (Allocation will be made inside the 'while' loop below.)
// Buffer length, in bytes.
// Initialize with some initial length that you expect to succeed at the first API call.
UINT32 bufferLength = /* ... */;
LONG returnCode = ERROR_INSUFFICIENT_BUFFER;
while (returnCode == ERROR_INSUFFICIENT_BUFFER)
//Allocate buffer of specified length
buffer.reset( BYTE[bufferLength] );
//Or, in C++14, could use make_unique() instead, e.g.
//buffer = std::make_unique(bufferLength);
//Call some Win32 API.
//If the size of the buffer (stored in 'bufferLength') is not big enough,
//the API will return ERROR_INSUFFICIENT_BUFFER, and the required size
//in the [in, out] parameter 'bufferLength'.
//In that case, there will be another try in the next loop iteration
//(with the allocation of a bigger buffer).
//Else, we'll exit the while loop body, and there will be either a failure
//different from ERROR_INSUFFICIENT_BUFFER, or the call will be successful
//and the required information will be available in the buffer.
returnCode = ::SomeApiCall(inParam1, inParam2, inParam3,
&bufferLength,//size of output buffer
buffer.get(), //output buffer pointer
//Handle failure, or throw exception, etc.
// All right!
// Do some processing with the returned information...