Right now my class has a constructor, copy constructor and copy assignment operator which all do the same thing at first (allocating memory). The destructor is deallocating the memory.
class Register
{
public:
Register()
{
_trampoline_address = reinterpret_cast<BYTE*>(VirtualAlloc(nullptr, _trampoline_size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE));
if (_trampoline_address == nullptr)
{
throw my_exception("Could not allocate memory for trampoline function.");
}
//....
}
~Register()
{
if (_trampoline_address != nullptr)
{
debug(VirtualFree(_trampoline_address, 0, MEM_RELEASE));
}
}
Register(const Register& other)
{
_trampoline_address = reinterpret_cast<BYTE*>(VirtualAlloc(nullptr, _trampoline_size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE));
if (_trampoline_address == nullptr)
{
throw my_exception("Could not allocate memory for trampoline function.");
}
//...
}
Register& operator= (const Register& other)
{
_trampoline_address = reinterpret_cast<BYTE*>(VirtualAlloc(nullptr, _trampoline_size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE));
if (_trampoline_address == nullptr)
{
throw my_exception("Could not allocate memory for trampoline function.");
}
//....
}
private:
BYTE* _trampoline_address;
static const int _trampoline_size = 20;
};
I thought about outsourcing the allocation algorithm because I use it 3 times, but I don't want that other instances of the same class type can access that function.
So what would be the proper solution to allocate memory in 3 functions in a RAII class?