From 7f4326bd2ded676097021d6b634a70a790a3b9ae Mon Sep 17 00:00:00 2001 From: dmalcolm Date: Mon, 18 Aug 2014 19:50:38 +0000 Subject: Introduce safe_as_a gcc/ 2014-08-18 David Malcolm * is-a.h (template safe_as_a ) New function. git-svn-id: svn+ssh://gcc.gnu.org/svn/gcc/trunk@214117 138bc75d-0d04-0410-961f-82ee72b054a4 --- gcc/ChangeLog | 4 ++++ gcc/is-a.h | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/gcc/ChangeLog b/gcc/ChangeLog index 55b41ae582f..bc5c327b931 100644 --- a/gcc/ChangeLog +++ b/gcc/ChangeLog @@ -1,3 +1,7 @@ +2014-08-18 David Malcolm + + * is-a.h (template safe_as_a ) New function. + 2014-08-18 Jan Hubicka * ipa-visibility.c (update_visibility_by_resolution_info): Do no turn UNDEF diff --git a/gcc/is-a.h b/gcc/is-a.h index a14e344761a..176066b42bc 100644 --- a/gcc/is-a.h +++ b/gcc/is-a.h @@ -46,6 +46,14 @@ TYPE as_a (pointer) do_something_with (as_a *ptr); +TYPE safe_as_a (pointer) + + Like as_a (pointer), but where pointer could be NULL. This + adds a check against NULL where the regular is_a_helper hook for TYPE + assumes non-NULL. + + do_something_with (safe_as_a *ptr); + TYPE dyn_cast (pointer) Converts pointer to TYPE if and only if "is_a pointer". Otherwise, @@ -185,6 +193,22 @@ as_a (U *p) return is_a_helper ::cast (p); } +/* Similar to as_a<>, but where the pointer can be NULL, even if + is_a_helper doesn't check for NULL. */ + +template +inline T +safe_as_a (U *p) +{ + if (p) + { + gcc_checking_assert (is_a (p)); + return is_a_helper ::cast (p); + } + else + return NULL; +} + /* A generic checked conversion from a base type U to a derived type T. See the discussion above for when to use this function. */ -- cgit v1.2.1