std :: unique_ptr与Win32 LocalFree的自定义删除器 [英] std::unique_ptr with custom deleter for win32 LocalFree

查看:118
本文介绍了std :: unique_ptr与Win32 LocalFree的自定义删除器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有win32 API CommandLineToArgvW,该API返回了LPWSTR*和 警告我

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

CommandLineToArgvW为以下分配一块连续的内存 指向参数字符串和参数字符串的指针 他们自己;调用应用程序必须释放 不再需要的参数列表.要释放内存,请使用 一次调用LocalFree函数.

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 the LocalFree function.

请参阅 http://msdn.microsoft. com/en-us/library/windows/desktop/bb776391(v = vs.85).aspx

在上述情况下,释放内存的C ++惯用方式是什么?

What is a C++ idiomatic way to free the memory in the above case?

我当时正在考虑使用自定义删除器的std::unique_ptr,诸如此类:

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;
}

上面的代码有问题吗?

推荐答案

在我看来,这是正确的.您可以通过指定unique_ptr的删除器内联而不是为其创建函子来使其更加简洁.

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<LPWSTR, HLOCAL(__stdcall *)(HLOCAL)> 
      p( ::CommandLineToArgvW( L"cmd.exe p1 p2 p3", &n ), ::LocalFree );

或者,如果您不想弄乱LocalFree的签名和调用约定,则可以使用lambda进行删除.

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<LPWSTR, void(*)(LPWSTR *)> 
      p( ::CommandLineToArgvW( L"cmd.exe p1 p2 p3", &n ), 
         [](LPWSTR *ptr){ ::LocalFree( ptr ); } );

注意:首次编写此答案时,VS2010是可用的已发布VS版本.它不支持将无捕获的lambda转换为函数指针,因此您必须在第二个例子

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<LPWSTR, std::function<void(LPWSTR *)>> 
      p( ::CommandLineToArgvW( L"cmd.exe p1 p2 p3", &n ), 
         [](LPWSTR *ptr){ ::LocalFree( ptr ); } );

这篇关于std :: unique_ptr与Win32 LocalFree的自定义删除器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆