Pergunta

I'm new to C++ and need some help.

I want to make a template class/struct that handles HANDLE and other WINAPIs so far is this code:

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

I honestly don't think that its working and the compiler gives me a warning:

warning C4101: 'GlobalFn' : unreferenced local variable

I saw this code from the web and did some changes to it, and i don't know if this is the right way to do it?

Foi útil?

Solução

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.

Outras dicas

How about using the standard unique_ptr

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

(Or something like that).

I suspect the problem in your code is that the compiler doesn't see your GlobalFn as a function call, but as a protoptype (another "win" for Most Vexing Parse) - you shouldn't need to use WINAPI at all, just make it a templated function pointer:

template class Handle_Wrap { ... ~Handle_Wrap() { GlobalFn(data); } };

You'll probably also want to use add an operator type_to_open() { return data; }, so that you can use FindNextFile(hFind, ...), rather than having to rely on data being public.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top