From 0ca91ced2dab3654e78e4c465506d7baad3cbeeb Mon Sep 17 00:00:00 2001
From: Lioncash <mathew1800@gmail.com>
Date: Tue, 17 Nov 2020 20:09:55 -0500
Subject: [PATCH] virtual_buffer: Add compile-time type-safety guarantees with
 VirtualBuffer

VirtualBuffer makes use of VirtualAlloc (on Windows) and mmap() (on
other platforms). Neither of these ensure that non-trivial objects are
properly constructed in the allocated memory.

To prevent potential undefined behavior occurring due to that, we can
add a static assert to loudly complain about cases where that is done.
---
 src/common/virtual_buffer.h | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/src/common/virtual_buffer.h b/src/common/virtual_buffer.h
index 363913d45..078e61c77 100644
--- a/src/common/virtual_buffer.h
+++ b/src/common/virtual_buffer.h
@@ -4,6 +4,7 @@
 
 #pragma once
 
+#include <type_traits>
 #include <utility>
 
 namespace Common {
@@ -14,6 +15,11 @@ void FreeMemoryPages(void* base, std::size_t size) noexcept;
 template <typename T>
 class VirtualBuffer final {
 public:
+    static_assert(
+        std::is_trivially_constructible_v<T>,
+        "T must be trivially constructible, as non-trivial constructors will not be executed "
+        "with the current allocator");
+
     constexpr VirtualBuffer() = default;
     explicit VirtualBuffer(std::size_t count) : alloc_size{count * sizeof(T)} {
         base_ptr = reinterpret_cast<T*>(AllocateMemoryPages(alloc_size));