1 /*
2  *  Copyright (c) 2006 Cyrille Berger <cberger@cberger.net>
3  *
4  *  This program is free software; you can redistribute it and/or modify
5  *  it under the terms of the GNU General Public License as published by
6  *  the Free Software Foundation; either version 2 of the License, or
7  *  (at your option) any later version.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License
15  *  along with this program; if not, write to the Free Software
16  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  */
18 
19 #include "kis_shared.h"
20 #include "kis_debug.h"
21 
22 
23 /**
24  * NOTE: The description of how Weak shared pointers system works:
25  *
26  * Every KisShared object has his own _sharedWeakReference pointer.
27  * This pointer holds QAtomicInt counter. When KisShared constructs
28  * itself, it increments _sharedWeakReference by one. When it dies -
29  * it decrements it. This is the only way how the number in the
30  * counter can become odd. Obviously, when the number falls to zero,
31  * the counter object is deleted.
32  *
33  * When a weak shared pointer is created, it gets the pointer and
34  * increments the counter by 2, so the parity of the number is kept
35  * unchanged. Now the counter is shared between the KisShared and
36  * KisWeakSharedPtr and the latter one can check the correctness
37  * of the pointer by checking parity!
38  */
39 
KisShared()40 KisShared::KisShared()
41 {
42     /**
43      * We can defer creation of a weak reference until
44      * better days... It gives us 41% better performance. ;)
45      */
46     _sharedWeakReference = 0;
47 }
48 
~KisShared()49 KisShared::~KisShared()
50 {
51     /**
52      * Check no-one references us
53      */
54     Q_ASSERT(_ref == 0);
55 
56     if(_sharedWeakReference && !_sharedWeakReference->deref())
57         delete _sharedWeakReference;
58 }
59