all: make nm_steal_pointer() and g_steal_pointer() more typesafe using typeof()

The previous code would always cast the argument to "void *", and thus
loose some type information.

For example,

  gulong variable = 0;

  g_steal_pointer(&variable);

would compile, when it shouldn't.

In general, we try to avoid redefining glib macros and headers. But we
really want those extra compile time checks that we can get, so let's do
it.
This commit is contained in:
Thomas Haller 2021-04-13 14:54:25 +02:00
parent 0e9aa8001a
commit 5bc511203e
No known key found for this signature in database
GPG key ID: 29C2366E4DFC5728
2 changed files with 19 additions and 33 deletions

View file

@ -407,30 +407,19 @@ _nm_g_hash_table_get_keys_as_array(GHashTable *hash_table, guint *length)
/*****************************************************************************/
static inline gpointer
_nm_g_steal_pointer(gpointer pp)
{
gpointer *ptr = (gpointer *) pp;
gpointer ref;
ref = *ptr;
*ptr = NULL;
return ref;
}
#if !GLIB_CHECK_VERSION(2, 44, 0)
static inline gpointer
g_steal_pointer(gpointer pp)
{
return _nm_g_steal_pointer(pp);
}
#endif
#ifdef g_steal_pointer
#undef g_steal_pointer
#endif
#define g_steal_pointer(pp) ((typeof(*(pp))) _nm_g_steal_pointer(pp))
#define g_steal_pointer(pp) \
({ \
typeof(*(pp)) *const _pp = (pp); \
typeof(**_pp) *const _p = *_pp; \
_nm_unused const void *const _p_type_check = _p; \
\
*_pp = NULL; \
_p; \
})
/*****************************************************************************/

View file

@ -753,18 +753,15 @@ _nm_auto_fclose(FILE **pfd)
/*****************************************************************************/
static inline void *
_nm_steal_pointer(void *pp)
{
void **ptr = (void **) pp;
void * ref;
ref = *ptr;
*ptr = NULL;
return ref;
}
#define nm_steal_pointer(pp) ((typeof(*(pp))) _nm_steal_pointer(pp))
#define nm_steal_pointer(pp) \
({ \
typeof(*(pp)) *const _pp = (pp); \
typeof(**_pp) *const _p = *_pp; \
_nm_unused const void *const _p_type_check = _p; \
\
*_pp = NULL; \
_p; \
})
/**
* nm_steal_int: