我在Win32 API CommandLineToArgvW
返回一個LPWSTR*
和 警告我說,的std ::的unique_ptr同爲Win32 LocalFree定製刪除
CommandLineToArgvW
分配的連續內存塊的指針 的說法字符串,爲參數字符串 自己;當調用應用程序不再需要時,調用應用程序必須釋放參數列表所使用的內存。要釋放內存,請使用 單次調用LocalFree
函數。
見 http://msdn.microsoft.com/en-us/library/windows/desktop/bb776391(v=vs.85).aspx
什麼是C++,以釋放在上述情況下的內存慣用的方法是什麼?
我在想一個std::unique_ptr
與定製刪除,這樣的事情:
#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;
}
有沒有在上面的代碼中的任何問題嗎?
你不需要'std :: function'作爲最後一個例子,我想:無狀態的lambda可以轉換爲函數指針。即'std :: unique_ptr p(...)' –
MSalters
2012-03-27 18:20:06
@MSalters我嘗試過,但是在VC10和g ++ 4.6.2下編譯失敗。前者的錯誤信息是'error C2664:'std :: unique_ptr <_Ty,_Dx> :: unique_ptr(wchar_t *,void(__stdcall * const&)(LPWSTR *))':不能從'匿名命名空間'轉換參數2 ::'到'void(__stdcall * const&)(LPWSTR *)' –
Praetorian
2012-03-27 18:25:41
@MSalters你是對的,捕獲的lambdas可以轉換爲函數指針,所以'std :: function'不是必需的。但是,VC10 [不實現此](https://connect.microsoft.com/VisualStudio/feedback/details/572138)。不知道我第一次嘗試使用g ++是如何搞砸的,但它確實有效。 – Praetorian 2012-03-27 22:32:06