worldsim/src/ownable.cpp

00001 /********************************************************************************
00002  *  WorldSim -- library for robot simulations                                   *
00003  *  Copyright (C) 2008-2011 Gianluca Massera <emmegian@yahoo.it>                *
00004  *                                                                              *
00005  *  This program is free software; you can redistribute it and/or modify        *
00006  *  it under the terms of the GNU General Public License as published by        *
00007  *  the Free Software Foundation; either version 2 of the License, or           *
00008  *  (at your option) any later version.                                         *
00009  *                                                                              *
00010  *  This program is distributed in the hope that it will be useful,             *
00011  *  but WITHOUT ANY WARRANTY; without even the implied warranty of              *
00012  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               *
00013  *  GNU General Public License for more details.                                *
00014  *                                                                              *
00015  *  You should have received a copy of the GNU General Public License           *
00016  *  along with this program; if not, write to the Free Software                 *
00017  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA  *
00018  ********************************************************************************/
00019 
00020 #include "ownable.h"
00021 
00022 namespace farsa {
00023 
00024 Ownable::Ownable() :
00025     m_owner(NULL),
00026     m_owned()
00027 {
00028 }
00029 
00030 Ownable::~Ownable()
00031 {
00032     // If I'm owned by some other object, removing myself from the list
00033     if (m_owner != NULL) {
00034         m_owner->removeFromOwned(this);
00035     }
00036 
00037     // Now deleting all owned objects I have to delete
00038     foreach (Owned o, m_owned) {
00039         if (o.destroy) {
00040             delete o.object;
00041         }
00042     }
00043 
00044     m_owned.clear();
00045 }
00046 
00047 void Ownable::setOwner(Ownable *owner, bool destroy)
00048 {
00049     // If I was owned by another object, first removing from my old owner
00050     if ((m_owner != NULL) && (m_owner != owner)) {
00051         m_owner->removeFromOwned(this);
00052     }
00053 
00054     m_owner = owner;
00055 
00056     // Now adding to the new owner
00057     if (m_owner != NULL) {
00058         m_owner->addToOwned(this, destroy);
00059     }
00060 }
00061 
00062 void Ownable::addToOwned(Ownable *obj, bool destroy)
00063 {
00064     m_owned.append(Owned(obj, destroy));
00065 }
00066 
00067 void Ownable::removeFromOwned(Ownable *obj)
00068 {
00069     m_owned.removeAll(Owned(obj));
00070 }
00071 
00072 }