As a mini project, I've been working on creating a Ptr
class to duplicate the mechanism of a pointer - the user should theoretically be able to use this class just like a real pointer without issue and without needing to interact with "actual" C++ pointers (besides some obvious syntax changes). The "memory store" is a very large array of bytes. However, I've been getting stuck on assigning dereferenced pointers (ex. *p1 = 123;
).
Essentially, the dereference operator has the signature of T& operator*()
, where it returns the T item by reference. The issue is that say someone tries to write something like *p1 = -12367890;
. This means that within my global memory array, at whatever index p1
is pointing to, I need to overwrite those contents with -12367890 so the memory reflects the assignment made. However, I'm not sure how to override this assignment operator to T such that I can modify memory. Could anyone give me some insight as to how I can somehow overload the dereferenced assignment operator so that I can make modifications to my Memory
class?
If it helps, my classes look something like the following (stripped down to their bare bones of course):
// constants.h
const int CAPACITY = 4000;
// memory.h
class Memory
{
public:
Memory();
....
private:
byte _memory[CAPACITY];
....
};
// ptr.h
template<typename T>
class Ptr
{
Ptr<T>(){}
T& operator*(); // ISSUE
....
private:
int _index;
};
// serialize.h (global functions for serialization)
template<typename T>
array<byte, sizeof(T)> serialize(const T& object);
template<typename T>
T& deserialize(const array<byte, sizeof(T)>& bytes, T& object);
The driver code for the program would look like this:
Ptr<int> p1; // initialize pointer
p1._new(); // allocate space in global memory array
*p1 = -12367890; // assign dereferenced pointer