-
Notifications
You must be signed in to change notification settings - Fork 13
/
com_ptr.h
64 lines (56 loc) · 1.41 KB
/
com_ptr.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#ifndef BASE_COM_PTR_H_
#define BASE_COM_PTR_H_
template <class T>
class _NoAddRefReleaseOnCComPtr : public T {
private:
STDMETHOD_(ULONG, AddRef)()=0;
STDMETHOD_(ULONG, Release)()=0;
};
template <class T>
class CComPtr {
public:
CComPtr() : _p(NULL) {}
CComPtr(T *x) : _p(x) { if (x) x->AddRef(); }
~CComPtr() {
if (_p)
_p->Release();
}
operator T*() const { return _p; }
T *get() const { return _p; }
T& operator*() const { return *_p; }
T** operator&() {
//DCHECK(_p == NULL);
return &_p; }
bool operator!() const throw() { return _p == NULL; }
_NoAddRefReleaseOnCComPtr<T>* operator->() const throw() {
//DCHECK(_p != NULL);
return (_NoAddRefReleaseOnCComPtr<T>*)_p;
}
HRESULT CoCreateInstance(__in REFCLSID rclsid, __in_opt LPUNKNOWN pUnkOuter = NULL, __in DWORD dwClsContext = CLSCTX_ALL) throw() {
//DCHECK(_p == NULL);
return ::CoCreateInstance(rclsid, pUnkOuter, dwClsContext, __uuidof(T), (void**)&_p);
}
// Release the interface and set to NULL
void Release() throw() {
T* pTemp = _p;
if (pTemp) {
_p = NULL;
pTemp->Release();
}
}
// Attach to an existing interface (does not AddRef)
void Attach(T* p2) throw() {
if (_p)
_p->Release();
_p = p2;
}
// Detach the interface (does not Release)
T* Detach() throw() {
T* pt = _p;
_p = NULL;
return pt;
}
private:
T *_p;
};
#endif // BASE_COM_PTR_H_