Debian Codegraph @

include/deal.II/base/observer_pointer.h

raw
1 // ------------------------------------------------------------------------
2 //
3 // SPDX-License-Identifier: LGPL-2.1-or-later
4 // Copyright (C) 1998 - 2025 by the deal.II authors
5 //
6 // This file is part of the deal.II library.
7 //
8 // Part of the source code is dual licensed under Apache-2.0 WITH
9 // LLVM-exception OR LGPL-2.1-or-later. Detailed license information
10 // governing the source code and code contributions can be found in
11 // LICENSE.md and CONTRIBUTING.md at the top level directory of deal.II.
12 //
13 // ------------------------------------------------------------------------
14
15 #ifndef dealii_observer_pointer_h
16 #define dealii_observer_pointer_h
17
18
19 #include <deal.II/base/config.h>
20
21 #include <deal.II/base/enable_observer_pointer.h>
22 #include <deal.II/base/exceptions.h>
23
24 #include <atomic>
25 #include <string>
26 #include <typeinfo>
27
28 DEAL_II_NAMESPACE_OPEN
29
30 /**
31 * This class represents an "observer pointer", i.e., it is a pointer class
32 * like `std::unique_ptr` or `std::shared_ptr`, but it does not participate in
33 * managing the lifetime of the object pointed to -- we are simply observing
34 * an object passively that is owned by some other entity of the program, but
35 * we are not in charge of creating and destroying this object. In particular,
36 * the pointer may be pointing to a member variable of another object whose
37 * lifetime is not actively managed but is instead tied to the lifetime of
38 * the surrounding object of which it is a member.
39 *
40 * The class does, however, have mechanisms to ensure that the object pointed
41 * to remains alive at least as long as the pointer points to -- in other words,
42 * unlike a simple C-style `T*` variable, it can avoid the problem of
43 * [dangling pointers](https://en.wikipedia.org/wiki/Dangling_pointer). In other
44 * works, objects of the current type can be used like a regular
45 * pointer (i.e., using the `*p` and `p->` operators and
46 * through casting), but they make sure that the object pointed to is not
47 * deleted or moved from in the course of use of the pointer by signaling the
48 * pointee its use. This is achieved by keeping a use count for the pointed-to
49 * object (which for this purpose needs to be derived from the
50 * EnableObserverPointer class), and ensuring that the pointed-to
51 * object's destructor triggers an error if that use-count is larger than zero
52 * -- i.e., if there are still observing ObserverPointer objects pointing to it.
53 *
54 * Conceptually, ObserverPointer fills a gap between `std::unique_ptr` and
55 * `std::shared_ptr`. While the former makes it clear that there is a unique
56 * owner of an object (namely the scope in which the `std::unique_ptr` resides),
57 * it does not allow other places in a code base to point to the object. In
58 * contrast, `std::shared_ptr` allows many places to point to the same object,
59 * but none of them is the "owner" of the object: They all are, and the last
60 * one to stop pointing to the object is responsible for deleting it.
61 *
62 * ObserverPointer utilizes semantics in which one place owns an object and
63 * others can point to it. The owning place is responsible for destroying the
64 * object when it is no longer needed, and as mentioned above, this will trigger
65 * an error if other places are still pointing to it via ObserverPointer
66 * pointers.
67 *
68 * In practice, using this scheme, if you try to destroy an object to which
69 * observers still point via ObserverPointer objects, you will get an error that
70 * says that there are still observers of the object and that the object can
71 * consequently not be destroyed without creating "dangling" pointers. This
72 * is often not very helpful in *finding* where these pointers are. As a
73 * consequence, this class also provides two ways to annotate the observer
74 * count with information about what other places still observe an object.
75 * First, when initializing a ObserverPointer object with the address of the
76 * object pointed to, you can also attach a string that describes the
77 * observing location, and this string will then be shown in error messages
78 * listing all remaining observers. Second, if no such string is provided,
79 * the name second template argument `P` is used as the debug string. This
80 * allows to encode the observer information in the type of the ObserverPointer.
81 *
82 * @note Unlike `std::unique_ptr` and `std::shared_ptr`, ObserverPointer does
83 * NOT implement any memory handling. In particular, deleting a
84 * ObserverPointer does not delete the object because the semantics
85 * of this class are that it only *observes* an object, but does not
86 * take over ownership. As a consequence, this is a sure way of creating
87 * a memory leak:
88 * @code
89 * ObserverPointer<T> dont_do_this = new T;
90 * @endcode
91 * This is because here, no variable "owns" the object pointed to, and
92 * the destruction of the `dont_do_this` pointer does not trigger the
93 * release of the memory pointed to.
94 *
95 * @note This class correctly handles `const`-ness of an object, i.e.,
96 * a `ObserverPointer<const T>` really behaves as if it were a pointer
97 * to a constant object (disallowing write access when dereferenced), while
98 * `ObserverPointer<T>` is a mutable pointer.
99 *
100 * @dealiiConceptRequires{std::is_base_of_v<EnableObserverPointer,
101 * T>}
102 *
103 * @ingroup memory
104 */
105 template <typename T, typename P = void>
106 class ObserverPointer
107 {
108 public:
109 /**
110 * Standard constructor for null pointer. The id of this pointer is set to
111 * the name of the class P.
112 */
113 ObserverPointer();
114
115 /**
116 * Copy constructor for ObserverPointer. We do not copy the object subscribed
117 * to from <tt>tt</tt>, but subscribe ourselves to it again.
118 */
119 template <class Q>
120 ObserverPointer(const ObserverPointer<T, Q> &other);
121
122 /**
123 * Copy constructor for ObserverPointer. We do not copy the object subscribed
124 * to from <tt>tt</tt>, but subscribe ourselves to it again.
125 */
126 ObserverPointer(const ObserverPointer<T, P> &other);
127
128 /**
129 * Move constructor for ObserverPointer.
130 */
131 ObserverPointer(ObserverPointer<T, P> &&other) noexcept;
132
133 /**
134 * Constructor taking a normal pointer. If possible, i.e. if the pointer is
135 * not a null pointer, the constructor subscribes to the given object to
136 * lock it, i.e. to prevent its destruction before the end of its use.
137 *
138 * The <tt>id</tt> is used in the call to
139 * EnableObserverPointer::subscribe(id) and by ~ObserverPointer()
140 * in the call to EnableObserverPointer::unsubscribe().
141 */
142 ObserverPointer(T *t, const std::string &id);
143
144 /**
145 * Constructor taking a normal pointer. If possible, i.e. if the pointer is
146 * not a null pointer, the constructor subscribes to the given object to
147 * lock it, i.e. to prevent its destruction before the end of its use. The
148 * id of this pointer is set to the name of the class P.
149 */
150 ObserverPointer(T *t);
151
152 /**
153 * Destructor, removing the subscription.
154 */
155 ~ObserverPointer();
156
157 /**
158 * Assignment operator for normal pointers. The pointer subscribes to the
159 * new object automatically and unsubscribes to an old one if it exists. It
160 * will not try to subscribe to a null-pointer, but still delete the old
161 * subscription.
162 */
163 ObserverPointer<T, P> &
164 operator=(T *tt);
165
166 /**
167 * Assignment operator for ObserverPointer. The pointer subscribes to the new
168 * object automatically and unsubscribes to an old one if it exists.
169 */
170 template <class Q>
171 ObserverPointer<T, P> &
172 operator=(const ObserverPointer<T, Q> &other);
173
174 /**
175 * Assignment operator for ObserverPointer. The pointer subscribes to the new
176 * object automatically and unsubscribes to an old one if it exists.
177 */
178 ObserverPointer<T, P> &
179 operator=(const ObserverPointer<T, P> &other);
180
181 /**
182 * Move assignment operator for ObserverPointer.
183 */
184 ObserverPointer<T, P> &
185 operator=(ObserverPointer<T, P> &&other) noexcept;
186
187 /**
188 * Delete the object pointed to and set the pointer to nullptr. Note
189 * that unlike what the documentation of the class describes, *this
190 * function actually deletes the object pointed to*. That is, this
191 * function assumes a ObserverPointer's ownership of the object pointed to.
192 *
193 * @deprecated This function is deprecated. It does not use the
194 * semantics we usually use for this class, and its use is surely
195 * going to be confusing.
196 */
197 DEAL_II_DEPRECATED
198 void
199 clear();
200
201 /**
202 * Conversion to normal pointer.
203 */
204 operator T *() const;
205
206 /**
207 * Dereferencing operator. This operator throws an ExcNotInitialized() if the
208 * pointer is a null pointer.
209 */
210 T &
211 operator*() const;
212
213 /**
214 * Return underlying pointer. This operator throws an ExcNotInitialized() if
215 * the pointer is a null pointer.
216 */
217 T *
218 get() const;
219
220 /**
221 * Operator that returns the underlying pointer. This operator throws an
222 * ExcNotInitialized() if the pointer is a null pointer.
223 */
224 T *
225 operator->() const;
226
227 /**
228 * Exchange the pointers of this object and the argument. Since both the
229 * objects to which is pointed are subscribed to before and after, we do not
230 * have to change their subscription counters.
231 *
232 * Note that this function (with two arguments) and the respective functions
233 * where one of the arguments is a pointer and the other one is a C-style
234 * pointer are implemented in global namespace.
235 */
236 template <class Q>
237 void
238 swap(ObserverPointer<T, Q> &tt);
239
240 /**
241 * Swap pointers between this object and the pointer given. As this releases
242 * the object pointed to presently, we reduce its subscription count by one,
243 * and increase it at the object which we will point to in the future.
244 *
245 * Note that we indeed need a reference of a pointer, as we want to change
246 * the pointer variable which we are given.
247 */
248 void
249 swap(T *&ptr);
250
251 /**
252 * Return an estimate of the amount of memory (in bytes) used by this class.
253 * Note in particular, that this only includes the amount of memory used by
254 * <b>this</b> object, not by the object pointed to.
255 */
256 std::size_t
257 memory_consumption() const;
258
259 private:
260 /**
261 * Pointer to the object we want to subscribe to.
262 */
263 T *pointer;
264
265 /**
266 * The identification for the subscriptor.
267 */
268 const std::string id;
269
270 /**
271 * The Smartpointer is invalidated when the object pointed to is destroyed
272 * or moved from.
273 */
274 std::atomic<bool> pointed_to_object_is_alive;
275 };
276
277
278 /**
279 * A type alias for the ObserverPointer class that makes sure the previous
280 * name of the class, SmartPointer, continues to be available.
281 *
282 * @deprecated Use the new name of the class, ObserverPointer, instead.
283 */
284 template <typename T, typename P = void>
285 using SmartPointer DEAL_II_DEPRECATED_EARLY_WITH_COMMENT(
286 "Use the new name of the class, ObserverPointer.") = ObserverPointer<T, P>;
287
288
289 /* --------------------- inline Template functions ------------------------- */
290
291
292 template <typename T, typename P>
293 inline ObserverPointer<T, P>::ObserverPointer()
294 : pointer(nullptr)
295 , id(typeid(P).name())
296 , pointed_to_object_is_alive(false)
297 {
298 static_assert(std::is_base_of_v<EnableObserverPointer, T>,
299 "This class can only be used if the first template argument "
300 "is a class derived from 'EnableObserverPointer'.");
301 }
302
303
304
305 template <typename T, typename P>
306 inline ObserverPointer<T, P>::ObserverPointer(T *t)
307 : pointer(t)
308 , id(typeid(P).name())
309 , pointed_to_object_is_alive(false)
310 {
311 static_assert(std::is_base_of_v<EnableObserverPointer, T>,
312 "This class can only be used if the first template argument "
313 "is a class derived from 'EnableObserverPointer'.");
314
315 if (t != nullptr)
316 t->subscribe(&pointed_to_object_is_alive, id);
317 }
318
319
320
321 template <typename T, typename P>
322 inline ObserverPointer<T, P>::ObserverPointer(T *t, const std::string &id)
323 : pointer(t)
324 , id(id)
325 , pointed_to_object_is_alive(false)
326 {
327 static_assert(std::is_base_of_v<EnableObserverPointer, T>,
328 "This class can only be used if the first template argument "
329 "is a class derived from 'EnableObserverPointer'.");
330
331 if (pointer != nullptr)
332 pointer->subscribe(&pointed_to_object_is_alive, id);
333 }
334
335
336
337 template <typename T, typename P>
338 template <class Q>
339 inline ObserverPointer<T, P>::ObserverPointer(
340 const ObserverPointer<T, Q> &other)
341 : pointer(other.pointer)
342 , id(other.id)
343 , pointed_to_object_is_alive(false)
344 {
345 static_assert(std::is_base_of_v<EnableObserverPointer, T>,
346 "This class can only be used if the first template argument "
347 "is a class derived from 'EnableObserverPointer'.");
348
349 if (other != nullptr)
350 {
351 Assert(other.pointed_to_object_is_alive,
352 ExcMessage("You can't copy a smart pointer object that "
353 "is pointing to an object that is no longer alive."));
354 pointer->subscribe(&pointed_to_object_is_alive, id);
355 }
356 }
357
358
359
360 template <typename T, typename P>
361 inline ObserverPointer<T, P>::ObserverPointer(
362 const ObserverPointer<T, P> &other)
363 : pointer(other.pointer)
364 , id(other.id)
365 , pointed_to_object_is_alive(false)
366 {
367 static_assert(std::is_base_of_v<EnableObserverPointer, T>,
368 "This class can only be used if the first template argument "
369 "is a class derived from 'EnableObserverPointer'.");
370
371 if (other != nullptr)
372 {
373 Assert(other.pointed_to_object_is_alive,
374 ExcMessage("You can't copy a smart pointer object that "
375 "is pointing to an object that is no longer alive."));
376 pointer->subscribe(&pointed_to_object_is_alive, id);
377 }
378 }
379
380
381
382 template <typename T, typename P>
383 inline ObserverPointer<T, P>::ObserverPointer(
384 ObserverPointer<T, P> &&other) noexcept
385 : pointer(other.pointer)
386 , id(other.id)
387 , pointed_to_object_is_alive(false)
388 {
389 static_assert(std::is_base_of_v<EnableObserverPointer, T>,
390 "This class can only be used if the first template argument "
391 "is a class derived from 'EnableObserverPointer'.");
392
393 if (other != nullptr)
394 {
395 Assert(other.pointed_to_object_is_alive,
396 ExcMessage("You can't move a smart pointer object that "
397 "is pointing to an object that is no longer alive."));
398
399 try
400 {
401 pointer->subscribe(&pointed_to_object_is_alive, id);
402 }
403 catch (...)
404 {
405 Assert(false,
406 ExcMessage(
407 "Calling subscribe() failed with an exception, but we "
408 "are in a function that cannot throw exceptions. "
409 "Aborting the program here."));
410 }
411
412 // Release the rhs object as if we had moved all members away from
413 // it directly:
414 other = nullptr;
415 }
416 }
417
418
419
420 template <typename T, typename P>
421 inline ObserverPointer<T, P>::~ObserverPointer()
422 {
423 static_assert(std::is_base_of_v<EnableObserverPointer, T>,
424 "This class can only be used if the first template argument "
425 "is a class derived from 'EnableObserverPointer'.");
426
427 if (pointed_to_object_is_alive && pointer != nullptr)
428 pointer->unsubscribe(&pointed_to_object_is_alive, id);
429 }
430
431
432
433 template <typename T, typename P>
434 inline void
435 ObserverPointer<T, P>::clear()
436 {
437 if (pointed_to_object_is_alive && pointer != nullptr)
438 {
439 pointer->unsubscribe(&pointed_to_object_is_alive, id);
440 delete pointer;
441 Assert(pointed_to_object_is_alive == false, ExcInternalError());
442 }
443 pointer = nullptr;
444 }
445
446
447
448 template <typename T, typename P>
449 inline ObserverPointer<T, P> &
450 ObserverPointer<T, P>::operator=(T *tt)
451 {
452 // optimize if no real action is requested
453 if (pointer == tt)
454 return *this;
455
456 // Let us unsubscribe from the current object
457 if (pointed_to_object_is_alive && pointer != nullptr)
458 pointer->unsubscribe(&pointed_to_object_is_alive, id);
459
460 // Then reset to the new object, and subscribe to it
461 pointer = tt;
462 if (tt != nullptr)
463 pointer->subscribe(&pointed_to_object_is_alive, id);
464
465 return *this;
466 }
467
468
469
470 template <typename T, typename P>
471 template <class Q>
472 inline ObserverPointer<T, P> &
473 ObserverPointer<T, P>::operator=(const ObserverPointer<T, Q> &other)
474 {
475 // if objects on the left and right
476 // hand side of the operator= are
477 // the same, then this is a no-op
478 if (&other == this)
479 return *this;
480
481 // Let us unsubscribe from the current object
482 if (pointed_to_object_is_alive && pointer != nullptr)
483 pointer->unsubscribe(&pointed_to_object_is_alive, id);
484
485 // Then reset to the new object, and subscribe to it
486 pointer = (other != nullptr ? other.get() : nullptr);
487 if (other != nullptr)
488 {
489 Assert(other.pointed_to_object_is_alive,
490 ExcMessage("You can't copy a smart pointer object that "
491 "is pointing to an object that is no longer alive."));
492 pointer->subscribe(&pointed_to_object_is_alive, id);
493 }
494 return *this;
495 }
496
497
498
499 template <typename T, typename P>
500 inline ObserverPointer<T, P> &
501 ObserverPointer<T, P>::operator=(const ObserverPointer<T, P> &other)
502 {
503 // if objects on the left and right
504 // hand side of the operator= are
505 // the same, then this is a no-op
506 if (&other == this)
507 return *this;
508
509 // Let us unsubscribe from the current object
510 if (pointed_to_object_is_alive && pointer != nullptr)
511 pointer->unsubscribe(&pointed_to_object_is_alive, id);
512
513 // Then reset to the new object, and subscribe to it
514 pointer = (other != nullptr ? other.get() : nullptr);
515 if (other != nullptr)
516 {
517 Assert(other.pointed_to_object_is_alive,
518 ExcMessage("You can't copy a smart pointer object that "
519 "is pointing to an object that is no longer alive."));
520 pointer->subscribe(&pointed_to_object_is_alive, id);
521 }
522 return *this;
523 }
524
525
526
527 template <typename T, typename P>
528 inline ObserverPointer<T, P> &
529 ObserverPointer<T, P>::operator=(ObserverPointer<T, P> &&other) noexcept
530 {
531 if (other == nullptr)
532 {
533 *this = nullptr;
534 }
535 // if objects on the left and right hand side of the operator= are
536 // the same, then this is a no-op
537 else if (&other != this)
538 {
539 // Let us unsubscribe from the current object
540 if (pointer != nullptr && pointed_to_object_is_alive)
541 pointer->unsubscribe(&pointed_to_object_is_alive, id);
542
543 // Then reset to the new object, and subscribe to it:
544 Assert(other.pointed_to_object_is_alive,
545 ExcMessage("You can't move a smart pointer object that "
546 "is pointing to an object that is no longer alive."));
547 pointer = other.get();
548 try
549 {
550 pointer->subscribe(&pointed_to_object_is_alive, id);
551 }
552 catch (...)
553 {
554 Assert(false,
555 ExcMessage(
556 "Calling subscribe() failed with an exception, but we "
557 "are in a function that cannot throw exceptions. "
558 "Aborting the program here."));
559 }
560
561 // Finally release the rhs object since we moved its contents
562 other = nullptr;
563 }
564 return *this;
565 }
566
567
568
569 template <typename T, typename P>
570 inline ObserverPointer<T, P>::operator T *() const
571 {
572 return pointer;
573 }
574
575
576
577 template <typename T, typename P>
578 inline T &
579 ObserverPointer<T, P>::operator*() const
580 {
581 Assert(pointer != nullptr, ExcNotInitialized());
582 Assert(pointed_to_object_is_alive,
583 ExcMessage("The object pointed to is not valid anymore."));
584 return *pointer;
585 }
586
587
588
589 template <typename T, typename P>
590 inline T *
591 ObserverPointer<T, P>::get() const
592 {
593 Assert(pointer != nullptr, ExcNotInitialized());
594 Assert(pointed_to_object_is_alive,
595 ExcMessage("The object pointed to is not valid anymore."));
596 return pointer;
597 }
598
599
600
601 template <typename T, typename P>
602 inline T *
603 ObserverPointer<T, P>::operator->() const
604 {
605 return this->get();
606 }
607
608
609
610 template <typename T, typename P>
611 template <class Q>
612 inline void
613 ObserverPointer<T, P>::swap(ObserverPointer<T, Q> &other)
614 {
615 if constexpr (running_in_debug_mode())
616 {
617 ObserverPointer<T, P> aux(pointer, id);
618 *this = other;
619 other = aux;
620 }
621 else
622 {
623 std::swap(pointer, other.pointer);
624 }
625 }
626
627
628
629 template <typename T, typename P>
630 inline void
631 ObserverPointer<T, P>::swap(T *&ptr)
632 {
633 if (pointed_to_object_is_alive && pointer != nullptr)
634 pointer->unsubscribe(pointed_to_object_is_alive, id);
635
636 std::swap(pointer, ptr);
637
638 if (pointer != nullptr)
639 pointer->subscribe(pointed_to_object_is_alive, id);
640 }
641
642
643
644 template <typename T, typename P>
645 inline std::size_t
646 ObserverPointer<T, P>::memory_consumption() const
647 {
648 return sizeof(ObserverPointer<T, P>);
649 }
650
651
652
653 // The following function is not strictly necessary but is an optimization
654 // for places where you call swap(p1,p2) with ObserverPointer objects p1, p2.
655 // Unfortunately, MS Visual Studio (at least up to the 2013 edition) trips
656 // over it when calling std::swap(v1,v2) where v1,v2 are std::vectors of
657 // ObserverPointer objects: it can't determine whether it should call std::swap
658 // or dealii::swap on the individual elements (see bug #184 on our Google Code
659 // site. Consequently, just take this function out of the competition for this
660 // compiler.
661 #ifndef _MSC_VER
662 /**
663 * Global function to swap the contents of two smart pointers. As both objects
664 * to which the pointers point retain to be subscribed to, we do not have to
665 * change their subscription count.
666 */
667 template <typename T, typename P, class Q>
668 inline void
669 swap(ObserverPointer<T, P> &t1, ObserverPointer<T, Q> &t2)
670 {
671 t1.swap(t2);
672 }
673 #endif
674
675
676 /**
677 * Global function to swap the contents of a smart pointer and a C-style
678 * pointer.
679 *
680 * Note that we indeed need a reference of a pointer, as we want to change the
681 * pointer variable which we are given.
682 */
683 template <typename T, typename P>
684 inline void
685 swap(ObserverPointer<T, P> &t1, T *&t2)
686 {
687 t1.swap(t2);
688 }
689
690
691
692 /**
693 * Global function to swap the contents of a C-style pointer and a smart
694 * pointer.
695 *
696 * Note that we indeed need a reference of a pointer, as we want to change the
697 * pointer variable which we are given.
698 */
699 template <typename T, typename P>
700 inline void
701 swap(T *&t1, ObserverPointer<T, P> &t2)
702 {
703 t2.swap(t1);
704 }
705
706 DEAL_II_NAMESPACE_CLOSE
707
708 #endif