summaryrefslogtreecommitdiffstats
path: root/auto_free.h
blob: 58290821b1a2b80e3094fdc8db8ca44180e3a905 (plain)
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
// -*- C++ -*-
// Copyright (C) 2008 Red Hat Inc.
//
// This file is part of systemtap, and is free software.  You can
// redistribute it and/or modify it under the terms of the GNU General
// Public License (GPL); either version 2, or (at your option) any
// later version.

#ifndef AUTO_FREE_H
#define AUTO_FREE_H 1
#include <cstdlib>

// Very simple auto_ptr-like class for protecting storage allocated
// with free().
class auto_free
{
public:
  auto_free(void* ptr) : _ptr(ptr) {}
  ~auto_free()
  {
    if (_ptr)
      std::free(_ptr);
  }
  void release()
  {
    _ptr = 0;
  }
private:
  // No copying allowed.
  auto_free(const auto_free& af);
  // No assignment either
  auto_free& operator=(const auto_free& rhs);
  void* _ptr;
};

// Use this to free a pointer whose value may change after the initial
// allocation e.g., be realloced.
template <typename T>
class auto_free_ref
{
public:
  typedef T pointer_type;
  auto_free_ref(pointer_type& ptr) : _ptr(ptr)
  {
  }
  ~auto_free_ref()
  {
    if (_ptr)
      std::free(_ptr);
  }
private:
  // No copying allowed.
  auto_free_ref(const auto_free_ref& af);
  // No assignment either
  auto_free_ref& operator=(const auto_free_ref& rhs);
  pointer_type& _ptr;
};
#endif