xref: /haiku/src/tests/add-ons/print/ppd/shared/AutoDelete.h (revision 1e60bdeab63fa7a57bc9a55b032052e95a18bd2c)
1 /*
2  * Copyright 2008, Haiku.
3  * Distributed under the terms of the MIT license.
4  *
5  * Authors:
6  *		Michael Pfeiffer <laplace@users.sourceforge.net>
7  */
8 
9 #ifndef _AUTO_DELETE_H
10 #define _AUTO_DELETE_H
11 
12 #include <stdlib.h>
13 
14 /*
15 Typical usage of this class:
16 
17 AClass* Klass::Method(int arg) {
18 	AutoDelete<AClass> variable(new AClass());
19 
20 	if (!IsValid(arg)) {
21 		...
22 		// AutoDelete automatically deletes the AClass object.
23 		return NULL;
24 	}
25 
26 	variable.Get()->MethodOfAClass();
27 
28 	// Use Release() to prevent deletion of AClass object.
29 	return variable.Release();
30 }
31 */
32 
33 template <class Tp>
34 class AutoDelete {
35 private:
36 	Tp*  fObject;
37 	bool fOwnsObject;
38 
39 	// Deletes the object if it owns it
40 	void Delete()
41 	{
42 		if (fOwnsObject) {
43 			delete fObject; fObject = NULL;
44 		}
45 	}
46 
47 public:
48 
49 	// Sets the object the class owns
50 	AutoDelete(Tp* object = NULL) : fObject(object), fOwnsObject(true) { }
51 
52 	// Deletes the object if it owns it
53 	virtual ~AutoDelete()
54 	{
55 		Delete();
56 	}
57 
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)
62 	{
63 		if (fObject == object) return;
64 
65 		Delete();
66 		fOwnsObject = true;
67 		fObject = object;
68 	}
69 
70 	// Returns the object
71 	Tp* Get()
72 	{
73 		return fObject;
74 	}
75 
76 	// Returns the object and sets owning to false
77 	// The Get method can still be used to retrieve the object.
78 	Tp* Release()
79 	{
80 		fOwnsObject = false;
81 		return fObject;
82 	}
83 
84 	// Sets the owning flag
85 	void SetOwnsObject(bool ownsObject)
86 	{
87 		fOwnsObject = ownsObject;
88 	}
89 };
90 
91 
92 #endif
93