1

我是 C++ 新手,需要一些帮助。

我想制作一个模板class/到目前为止struct处理HANDLE和其他s 是这段代码:WINAPI

template <typename type_to_open, typename returntype, returntype (WINAPI * GlobalFn)(             
type_to_open )> class Handle_Wrap {
public:
type_to_open data;
Handle_Wrap (type_to_open in_data) { data = in_data; }
~Handle_Wrap() { returntype (WINAPI * GlobalFn)( type_to_open );}
};

Handle_Wrap <HANDLE, BOOL, ::FindClose> hFind ( FindFirstFileA (pattern.c_str(), &ffd) );

老实说,我不认为它的工作和编译器给了我一个警告:

warning C4101: 'GlobalFn' : unreferenced local variable

我从网上看到这段代码并对其进行了一些更改,我不知道这是否是正确的方法?

4

2 回答 2

1

The problem is in your destructor. You repeat the declaration of GlobalFn, rather than call it. It should be:

~HandleWrap() { (*GlobalFn)( data ); }

Also, do you want to make this class copyable, movable or neither? If neither, you should take steps to prevent any of the relevant compiler generated defaults; otherwise, you'll need to provide the corresponding constructors (and possibly assignment operators). If copyable, you'll also need some sort of counter, shared between all of the copies, so that only the last destructor frees the handle. For movable (probably the best solution, if you can be sure of having C++11), you'll need a move constructor, which does something to ensure that the destructor of the moved from object is a no-op.

于 2013-08-28T12:44:54.457 回答
0

如何使用标准unique_ptr

 std::unique_ptr<HANDLE, ::FindClose> hFind = FindFirstFileA(...);

(或类似的东西)。

我怀疑您的代码中的问题是编译器没有将您GlobalFn视为函数调用,而是将其视为原型(Most Vexing Parse 的另一个“胜利”)-您根本不需要使用WINAPI,只需将其设为模板函数指针:

模板类 Handle_Wrap { ... ~Handle_Wrap() { GlobalFn(data); } };

您可能还想使用 add an operator type_to_open() { return data; },以便您可以使用FindNextFile(hFind, ...),而不必依赖于data公开。

于 2013-08-28T12:25:24.553 回答