Skip to content

Commit a3f5f7d

Browse files
committed
Account for alignment reqs of the control block
1 parent 2b4c984 commit a3f5f7d

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

include/oup/observable_unique_ptr.hpp

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -878,14 +878,16 @@ auto make_observable(Args&&... args) {
878878
new object_type(std::forward<Args>(args)...));
879879
}
880880
} else {
881-
// Pre-allocate memory
882-
constexpr std::size_t block_size = sizeof(control_block_type);
883-
constexpr std::size_t object_size = sizeof(object_type);
884-
constexpr std::size_t object_align = alignof(object_type);
885-
constexpr std::size_t align_padding = object_align - 1 - ((block_size - 1) % object_align);
886-
constexpr std::size_t obj_offset = block_size + align_padding;
887-
888-
std::byte* buffer = reinterpret_cast<std::byte*>(operator new(obj_offset + object_size));
881+
// Pre-allocate memory, properly aligned for both the control block and the object
882+
constexpr std::size_t block_size = sizeof(control_block_type);
883+
constexpr std::size_t block_align = alignof(control_block_type);
884+
constexpr std::size_t obj_size = sizeof(object_type);
885+
constexpr std::size_t obj_align = alignof(object_type);
886+
constexpr std::size_t obj_offset = obj_align * (1 + (block_size - 1) / obj_align);
887+
constexpr std::size_t alloc_align = block_align > obj_align ? block_align : obj_align;
888+
889+
std::byte* buffer = reinterpret_cast<std::byte*>(operator new (
890+
obj_offset + obj_size, std::align_val_t{alloc_align}));
889891

890892
try {
891893
// Construct control block first

0 commit comments

Comments
 (0)