File: cotaskmemptr.h

package info (click to toggle)
wxpython4.0 4.2.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 232,540 kB
  • sloc: cpp: 958,937; python: 233,059; ansic: 150,441; makefile: 51,662; sh: 8,687; perl: 1,563; javascript: 584; php: 326; xml: 200
file content (85 lines) | stat: -rw-r--r-- 2,113 bytes parent folder | download | duplicates (4)
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
///////////////////////////////////////////////////////////////////////////////
// Name:        wx/msw/private/cotaskmemptr.h
// Purpose:     RAII class for pointers to be freed with ::CoTaskMemFree().
// Author:      PB
// Created:     2020-06-09
// Copyright:   (c) 2020 wxWidgets team
// Licence:     wxWindows licence
///////////////////////////////////////////////////////////////////////////////

#ifndef _WX_MSW_PRIVATE_COTASKMEMPTR_H_
#define _WX_MSW_PRIVATE_COTASKMEMPTR_H_

// needed for ::CoTaskMem{Alloc|Free}()
#include "wx/msw/wrapwin.h"

// ----------------------------------------------------------------------------
// wxCoTaskMemPtr: A barebone RAII class for pointers to be freed with ::CoTaskMemFree().
// ----------------------------------------------------------------------------

template <class T>
class wxCoTaskMemPtr
{
public:
    typedef T element_type;

    wxCoTaskMemPtr()
        : m_ptr(NULL)
    {}

    explicit wxCoTaskMemPtr(T* ptr)
        : m_ptr(ptr)
    {}

    // Uses ::CoTaskMemAlloc() to allocate size bytes.
    explicit wxCoTaskMemPtr(size_t size)
        : m_ptr(static_cast<T*>(::CoTaskMemAlloc(size)))
    {}

    ~wxCoTaskMemPtr()
    {
        ::CoTaskMemFree(m_ptr);
    }

    void reset(T* ptr = NULL)
    {
        if ( m_ptr != ptr )
        {
            ::CoTaskMemFree(m_ptr);
            m_ptr = ptr;
        }
    }

    operator T*() const
    {
        return m_ptr;
    }

    // It would be better to forbid direct access completely but we do need it,
    // so provide it but it can only be used to initialize the pointer,
    // not to modify an existing one.
    T** operator&()
    {
        wxASSERT_MSG(!m_ptr,
                     wxS("Can't get direct access to initialized pointer"));

        return &m_ptr;
    }

    // Gives up the ownership of the pointer,
    // making the caller responsible for freeing it.
    T* release()
    {
        T* ptr(m_ptr);

        m_ptr = NULL;
        return ptr;
    }

private:
    T* m_ptr;

    wxDECLARE_NO_COPY_TEMPLATE_CLASS(wxCoTaskMemPtr, T);
};

#endif // _WX_MSW_PRIVATE_COTASKMEMPTR_H_