]> https://gitweb.dealii.org/ - dealii.git/commitdiff
Disallow copying SmartPointers pointing to dead objects. 17416/head
authorWolfgang Bangerth <bangerth@colostate.edu>
Mon, 12 Aug 2024 14:27:21 +0000 (08:27 -0600)
committerWolfgang Bangerth <bangerth@colostate.edu>
Mon, 12 Aug 2024 14:27:21 +0000 (08:27 -0600)
include/deal.II/base/smartpointer.h

index 73728ca04741159cdf4948737f40ae7548f01e4f..5e39ead3f84ef7d8f9a30f9bb2b82ac0b2628471 100644 (file)
@@ -305,8 +305,13 @@ inline SmartPointer<T, P>::SmartPointer(const SmartPointer<T, Q> &tt)
   , id(tt.id)
   , pointed_to_object_is_alive(false)
 {
-  if (tt.pointed_to_object_is_alive && t != nullptr)
-    t->subscribe(&pointed_to_object_is_alive, id);
+  if (tt != nullptr)
+    {
+      Assert(tt.pointed_to_object_is_alive,
+             ExcMessage("You can't copy a smart pointer object that "
+                        "is pointing to an object that is no longer alive."));
+      t->subscribe(&pointed_to_object_is_alive, id);
+    }
 }
 
 
@@ -317,8 +322,13 @@ inline SmartPointer<T, P>::SmartPointer(const SmartPointer<T, P> &tt)
   , id(tt.id)
   , pointed_to_object_is_alive(false)
 {
-  if (tt.pointed_to_object_is_alive && t != nullptr)
-    t->subscribe(&pointed_to_object_is_alive, id);
+  if (tt != nullptr)
+    {
+      Assert(tt.pointed_to_object_is_alive,
+             ExcMessage("You can't copy a smart pointer object that "
+                        "is pointing to an object that is no longer alive."));
+      t->subscribe(&pointed_to_object_is_alive, id);
+    }
 }
 
 
@@ -419,8 +429,13 @@ SmartPointer<T, P>::operator=(const SmartPointer<T, Q> &tt)
 
   // Then reset to the new object, and subscribe to it
   t = (tt != nullptr ? tt.get() : nullptr);
-  if (tt.pointed_to_object_is_alive && tt != nullptr)
-    t->subscribe(&pointed_to_object_is_alive, id);
+  if (tt != nullptr)
+    {
+      Assert(tt.pointed_to_object_is_alive,
+             ExcMessage("You can't copy a smart pointer object that "
+                        "is pointing to an object that is no longer alive."));
+      t->subscribe(&pointed_to_object_is_alive, id);
+    }
   return *this;
 }
 
@@ -442,9 +457,13 @@ SmartPointer<T, P>::operator=(const SmartPointer<T, P> &tt)
 
   // Then reset to the new object, and subscribe to it
   t = (tt != nullptr ? tt.get() : nullptr);
-  if (tt.pointed_to_object_is_alive && tt != nullptr)
-    t->subscribe(&pointed_to_object_is_alive, id);
-
+  if (tt != nullptr)
+    {
+      Assert(tt.pointed_to_object_is_alive,
+             ExcMessage("You can't copy a smart pointer object that "
+                        "is pointing to an object that is no longer alive."));
+      t->subscribe(&pointed_to_object_is_alive, id);
+    }
   return *this;
 }
 

In the beginning the Universe was created. This has made a lot of people very angry and has been widely regarded as a bad move.

Douglas Adams


Typeset in Trocchi and Trocchi Bold Sans Serif.