I built a class which stores a buffer type, its size, and a pointer to that buffer.
The intention is to access the buffer through that pointer to perform all the operations.
The issue is, when I assign an instance of this class to another like so:
buffer = ExampleUsage(10);
the pointer breaks.
Here are the two classes (buffer and a usage for that buffer):
First the buffer I use in my example:
class ExampleBuffer {
public:
ExampleBuffer() :size(0), buffer(0) {}
ExampleBuffer(size_t size) {
this->size = size;
buffer = vector<int>(size);
}
void Draw(int index, int val) {
buffer[index] = val;
}
int Get(int index) {
return buffer[index];
}
protected:
int size;
vector<int> buffer;
};
Next the class I use to access the buffer and perform operations on it:
class ExampleUsage {
public:
ExampleUsage() :
size(0),
buffer(0),
ptr(&buffer) {}
ExampleUsage(int size) :
size(size),
buffer(size),
ptr(&buffer) {}
void Draw(int index, int val) {
ptr->Draw(index, val);
}
int Get(int index) {
return ptr->Get(index);
}
protected:
int size;
ExampleBuffer buffer;
ExampleBuffer* ptr;
};
Here's a program to demonstrate the problem.
class SomeClass {
public:
void Init() {
buffer = ExampleUsage(10);
}
void DoStuff() {
buffer.Draw(0, 1234);
}
protected:
ExampleUsage buffer;
};
int main() {
SomeClass example;
example.Init();
example.DoStuff();
}
When it executes, it initializes ExampleUsage
with its default constructor
and then another instance is generated in the Init()
method of SomeClass
and assigned to buffer
.
Then the method DoStuff()
is called, which executes the buffer's Draw()
method and from there, the pointer should access the stored ExampleBuffer
but it points to a nullptr instead leading to an exception.
I know that if I remove the line:
buffer = ExampleUsage(10);
and instead replace it with something like:
buffer.Init(10); //hypothetical method to initialize the class.
it will work.
Why does the pointer in ExampleUsage
not point to the ExampleBuffer
in this program?