From 152c6c54e4e009a64c07884ad17210e448a3244b Mon Sep 17 00:00:00 2001 From: Julian Eisel Date: Mon, 17 Feb 2025 16:18:04 +0100 Subject: [PATCH] Cleanup: Improve API comment for `MEM_new()` 194e233d863d6 caused a discussion in the chat about the initialization behavior of `MEM_new()`, and agreement was to not rely on zero-initialization ever. Noted this in the API comment now. Some people found the existing comment useful but it still left some questions. Tried to clarify that now. This is a crucial memory management function, it's important to have behavior documented well, even if a full explanation is out-of-scope. Also added another link in case people want to check more details. Pull Request: https://projects.blender.org/blender/blender/pulls/134577 --- intern/guardedalloc/MEM_guardedalloc.h | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/intern/guardedalloc/MEM_guardedalloc.h b/intern/guardedalloc/MEM_guardedalloc.h index 6f500c9e4c2..83d2d33ace8 100644 --- a/intern/guardedalloc/MEM_guardedalloc.h +++ b/intern/guardedalloc/MEM_guardedalloc.h @@ -293,11 +293,15 @@ void MEM_use_guarded_allocator(void); * Allocate new memory for an object of type #T, and construct it. * #MEM_delete must be used to delete the object. Calling #MEM_freeN on it is illegal. * - * Note that when no arguments are passed, C++ will do recursive member-wise value initialization. - * That is because C++ differentiates between creating an object with `T` (default initialization) - * and `T()` (value initialization), whereby this function does the latter. Value initialization - * rules are complex, but for C-style structs, memory will be zero-initialized. So this doesn't - * match a `malloc()`, but a `calloc()` call in this case. See https://stackoverflow.com/a/4982720. + * Do not assume that this ever zero-initializes memory (even when it does), explicitly initialize. + * + * Although calling this without arguments will cause zero-initialization for many types, simple + * changes to the type can break this. Basic explanation: + * With no arguments, this will initialize using `T()` (value initialization) not `T` (default + * initialization). Details are involved, but for "C-style" structs ("Plain old Data" structs or + * structs with a compiler generated constructor) memory will be zero-initialized. A change like + * simply adding a custom default constructor would change initialization behavior. + * See: https://stackoverflow.com/a/4982720, https://stackoverflow.com/a/620402 */ template inline T *MEM_new(const char *allocation_name, Args &&...args)