I have the win32 API CommandLineToArgvW
which returns a LPWSTR*
and
warns me that
CommandLineToArgvW
allocates a block of contiguous memory for pointers to the argument strings, and for the argument strings themselves; the calling application must free the memory used by the argument list when it is no longer needed. To free the memory, use a single call to theLocalFree
function.
See http://msdn.microsoft.com/en-us/library/windows/desktop/bb776391(v=vs.85).aspx
What is a C++ idiomatic way to free the memory in the above case?
I was thinking to a std::unique_ptr
with a custom deleter, something like that:
#include <Windows.h>
#include <memory>
#include <iostream>
template< class T >
struct Local_Del
{
void operator()(T*p){::LocalFree(p);}
};
int main(int argc, char* argv[])
{
{
int n = 0;
std::unique_ptr< LPWSTR, Local_Del< LPWSTR > > p( ::CommandLineToArgvW(L"cmd.exe p1 p2 p3",&n) );
for ( int i = 0; i < n; i++ ) {
std::wcout << p.get()[i] << L"\n";
}
}
return 0;
}
Is there any problem in the above code?