From 5b5253ba2f8697d8b96decea80742258bf3ce0bb Mon Sep 17 00:00:00 2001 From: Wolfgang Bangerth Date: Mon, 12 Aug 2024 08:27:21 -0600 Subject: [PATCH] Disallow copying SmartPointers pointing to dead objects. --- include/deal.II/base/smartpointer.h | 37 ++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/include/deal.II/base/smartpointer.h b/include/deal.II/base/smartpointer.h index 73728ca047..5e39ead3f8 100644 --- a/include/deal.II/base/smartpointer.h +++ b/include/deal.II/base/smartpointer.h @@ -305,8 +305,13 @@ inline SmartPointer::SmartPointer(const SmartPointer &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::SmartPointer(const SmartPointer &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::operator=(const SmartPointer &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::operator=(const SmartPointer &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; } -- 2.39.5