template class mrpt::StackAlloc

Overview

Portable fast allocator: uses the stack for small buffers, heap otherwise.

IMPORTANT: alloca() memory lives only in the calling function’s stack frame. Wrapping alloca() inside a helper/method means the memory is freed when that helper returns — leaving a dangling pointer. Use the MRPT_STACK_ALLOC() macro to ensure the alloca() call stays in the caller.

#include <mrpt/core/StackAlloc.h>

template <typename T = std::byte>
class StackAlloc
{
public:
    // construction

    StackAlloc(T* ptr, std::size_t count, bool on_heap);
    StackAlloc(std::size_t count);
    StackAlloc(const StackAlloc&);
    StackAlloc(StackAlloc&&);

    // methods

    StackAlloc& operator = (const StackAlloc&);
    StackAlloc& operator = (StackAlloc&&);
    T* get();
    const T* get() const;
    std::size_t size() const;
};

Construction

StackAlloc(T* ptr, std::size_t count, bool on_heap)

Construct from a pointer already obtained via alloca (or malloc).

Prefer the MRPT_STACK_ALLOC() macro over calling this directly.

StackAlloc(std::size_t count)

Heap-only constructor (safe fallback, no macro needed).