Skip to content

Mem and MemA Termplate Class

Rob Nelson edited this page Feb 7, 2021 · 1 revision

Mem is a template class that is a container for a dynamically sized memory array of the type specified.

The memory contained in Mem is automatically deleted when it is removed from the current scope.

Mem may be declared as a specific size, filled later, or reallocated dynamically.

The Mem template class guarantees memory and pointer safety by managing and deleting allocated memory. Once the Mem object is defined, deleting memory is not necessary -- it is handled when the Mem object is destructed.

Mem objects are designed to be placed on the stack to contain memory larger than the stack, or as a reference in a class to contain a pointer to memory that will be automatically deleted when the parent class is destroyed.

Bounds Checking vs. Direct Access

The Mem object is defined to to work with both safe bounds-checking environment as well as direct access to memory information.

Safe Bounds Checking Usage

To use the Mem object with bounds-checking in a safe manner, to avoid accessing memory outside of the array, possibly causing a crash or memory corruption, you can index directly into the memory array.

For example,

Mem<int> MyMemory(100);
MyMemory[25] = MyValue;
MyMemory[500] = MyValue2; 

will successfully fill MyMemory[25], but throw an exception when MyMemory[500] is filled.

Direct Access

For direct access, simply assign a pointer to the memory and directly acess it.

Mem MyMemory(iMemoryNeeded) auto fpMemory = &*MyMemory; auto fpMemory = MyMemory.GetData(); double * fpMemory = MyMemory;

The above three methods are all ways to get the memory address of the Mem array. Note that

auto fpMemory = MyMemory;

Examples:

Mem<int> MyMemory;      // Declares an empty Mem object called MyMemory which an store int types
Mem<int> MyMemory(100); // Declares a Mem object that contains an int[100] array.

Mem deletion

The memory array is deleted when the Mem object goes out of scope. For example:

int MyFunction()
{
    Mem<int> MyMemory(100);
    DoSomething with(Mem); 
    return 0;
}

MyMemory and the int[100] array that was allocated is deleted when MyFunction returns;

When returning the same Memory object, such as

Mem MyFunction()
{
    Mem<int> MyMemory(100);
    DoSomethingwith(Mem);
    return Mem;
}

The Mem object is moved to the return object.

Assigning and Copying Mem Objects

Clone this wiki locally