std::unique_ptr with custom deleter for win32 LocalFree

后端 未结 4 952
离开以前
离开以前 2021-02-12 23:24

I have the win32 API CommandLineToArgvW which returns a LPWSTR* and warns me that

CommandLineToArgvW allocates a

4条回答
  •  悲&欢浪女
    2021-02-13 00:12

    It looks correct to me. You could make it a little more succinct by specifying the unique_ptr's deleter inline rather than creating a functor for it.

    std::unique_ptr 
          p( ::CommandLineToArgvW( L"cmd.exe p1 p2 p3", &n ), ::LocalFree );
    

    Or, if you don't want to mess with LocalFree's signature and calling conventions you can use a lambda to do the deletion.

    std::unique_ptr 
          p( ::CommandLineToArgvW( L"cmd.exe p1 p2 p3", &n ), 
             [](LPWSTR *ptr){ ::LocalFree( ptr ); } );
    

    Note: At the time this answer was first written, VS2010 was the released VS version available. It doesn't support conversion of capture-less lambdas to function pointers, so you'd have to use std::function in the second example

    std::unique_ptr> 
          p( ::CommandLineToArgvW( L"cmd.exe p1 p2 p3", &n ), 
             [](LPWSTR *ptr){ ::LocalFree( ptr ); } );
    

提交回复
热议问题