Skip to content

Commit

Permalink
Modified "pretend_to_initialize" for c++ (#5920)
Browse files Browse the repository at this point in the history
In this case we actually have to initialize rather than just
do nothing. Fixes #5278.

* Move code to utility code file
  • Loading branch information
da-woods committed Feb 10, 2024
1 parent 8d477de commit a3942c8
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
3 changes: 2 additions & 1 deletion Cython/Compiler/ModuleNode.py
Expand Up @@ -866,7 +866,8 @@ def generate_module_preamble(self, env, options, cimported_modules, metadata, co
PyrexTypes.c_int_type.create_from_py_utility_code(env)

code.put(Nodes.branch_prediction_macros)
code.putln('static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; }')

self._put_setup_code(code, "PretendToInitialize")
code.putln('')
code.putln('#if !CYTHON_USE_MODULE_STATE')
code.putln('static PyObject *%s = NULL;' % env.module_cname)
Expand Down
24 changes: 24 additions & 0 deletions Cython/Utility/ModuleSetupCode.c
Expand Up @@ -2144,6 +2144,30 @@ static void __Pyx_FastGilFuncInit(void) {

#endif

///////////////////// PretendToInitialize ////////////////////////

#ifdef __cplusplus
// In C++ a variable must actually be initialized to make returning
// it defined behaviour, and there doesn't seem to be a viable compiler trick to
// avoid that.
#include <type_traits>
template <typename T>
static void __Pyx_pretend_to_initialize(T* ptr) {
// In C++11 we have enough introspection to work out which types it's actually
// necessary to apply this to (non-trivial types will have been initialized by
// the definition). Below C++11 just initialize everything.
#if __cplusplus > 201103L
if ((std::is_trivially_default_constructible<T>::value))
#endif
*ptr = T();
(void)ptr;
}
#else
// For C, taking an address of a variable is enough to make returning it
// defined behaviour.
static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; }
#endif

///////////////////// UtilityCodePragmas /////////////////////////

#ifdef _MSC_VER
Expand Down

0 comments on commit a3942c8

Please sign in to comment.