headers/bsd: Add sys/queue.h.
[haiku.git] / src / tests / add-ons / print / ppd / shared / AutoDelete.h
blob38193ffac28cb43997547d6eb71a03805612a1a0
1 /*
2 * Copyright 2008, Haiku.
3 * Distributed under the terms of the MIT license.
5 * Authors:
6 * Michael Pfeiffer <laplace@users.sourceforge.net>
7 */
9 #ifndef _AUTO_DELETE_H
10 #define _AUTO_DELETE_H
12 #include <stdlib.h>
15 Typical usage of this class:
17 AClass* Klass::Method(int arg) {
18 AutoDelete<AClass> variable(new AClass());
20 if (!IsValid(arg)) {
21 ...
22 // AutoDelete automatically deletes the AClass object.
23 return NULL;
26 variable.Get()->MethodOfAClass();
28 // Use Release() to prevent deletion of AClass object.
29 return variable.Release();
33 template <class Tp>
34 class AutoDelete {
35 private:
36 Tp* fObject;
37 bool fOwnsObject;
39 // Deletes the object if it owns it
40 void Delete()
42 if (fOwnsObject) {
43 delete fObject; fObject = NULL;
47 public:
49 // Sets the object the class owns
50 AutoDelete(Tp* object = NULL) : fObject(object), fOwnsObject(true) { }
52 // Deletes the object if it owns it
53 virtual ~AutoDelete()
55 Delete();
58 // Sets the object the class owns.
59 // Deletes a previously owned object and
60 // sets the owning flag for the new object.
61 void Set(Tp* object)
63 if (fObject == object) return;
65 Delete();
66 fOwnsObject = true;
67 fObject = object;
70 // Returns the object
71 Tp* Get()
73 return fObject;
76 // Returns the object and sets owning to false
77 // The Get method can still be used to retrieve the object.
78 Tp* Release()
80 fOwnsObject = false;
81 return fObject;
84 // Sets the owning flag
85 void SetOwnsObject(bool ownsObject)
87 fOwnsObject = ownsObject;
92 #endif