ownable.cpp
1 /********************************************************************************
2  * WorldSim -- library for robot simulations *
3  * Copyright (C) 2008-2011 Gianluca Massera <emmegian@yahoo.it> *
4  * *
5  * This program is free software; you can redistribute it and/or modify *
6  * it under the terms of the GNU General Public License as published by *
7  * the Free Software Foundation; either version 2 of the License, or *
8  * (at your option) any later version. *
9  * *
10  * This program is distributed in the hope that it will be useful, *
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13  * GNU General Public License for more details. *
14  * *
15  * You should have received a copy of the GNU General Public License *
16  * along with this program; if not, write to the Free Software *
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *
18  ********************************************************************************/
19 
20 #include "ownable.h"
21 
22 namespace farsa {
23 
25  m_owner(NULL),
26  m_owned()
27 {
28 }
29 
31 {
32  // If I'm owned by some other object, removing myself from the list
33  if (m_owner != NULL) {
34  m_owner->removeFromOwned(this);
35  }
36 
37  // Now deleting all owned objects I have to delete
38  foreach (Owned o, m_owned) {
39  if (o.destroy) {
40  delete o.object;
41  }
42  }
43 
44  m_owned.clear();
45 }
46 
47 void Ownable::setOwner(Ownable *owner, bool destroy)
48 {
49  // If I was owned by another object, first removing from my old owner
50  if ((m_owner != NULL) && (m_owner != owner)) {
51  m_owner->removeFromOwned(this);
52  }
53 
54  m_owner = owner;
55 
56  // Now adding to the new owner
57  if (m_owner != NULL) {
58  m_owner->addToOwned(this, destroy);
59  }
60 }
61 
62 void Ownable::addToOwned(Ownable *obj, bool destroy)
63 {
64  m_owned.append(Owned(obj, destroy));
65 }
66 
67 void Ownable::removeFromOwned(Ownable *obj)
68 {
69  m_owned.removeAll(Owned(obj));
70 }
71 
72 }
Ownable()
Constructor.
Definition: ownable.cpp:24
The structure with information about the owned object.
Definition: ownable.h:46
The base for all class that can have (and can be) an owner.
Definition: ownable.h:37
bool destroy
If true the object is automatically destroyed by the owner destructor.
Definition: ownable.h:80
void setOwner(Ownable *owner, bool destroy=true)
Sets the owner of this object.
Definition: ownable.cpp:47
virtual ~Ownable()
Destructor.
Definition: ownable.cpp:30
Ownable * object
The owned object.
Definition: ownable.h:74
Ownable * owner() const
Returns the owner of this object.
Definition: ownable.h:115