I want to implement a buffer with a managed variant similar to the following:
struct Buffer {
int size;
char *ptr;
void destruct() {
delete ptr;
}
};
struct MngdBuffer : Buffer {
MngdBuffer() : Buffer() {}
~MngdBuffer() {
destruct();
}
};
plus copy constructors, etc. This would allow a function to take a Buffer
and access its contents regardless of who owns the memory it points to. However, a problem is introduced when returning a MngdBuffer
from a function and putting the result in a Buffer
:
MngdBuffer func() {
MngdBuffer buf;
buf.ptr = new char;
buf.size = 1;
return buf;
}
int main() {
Buffer buf = func();
}
The destructor of MngdBuffer
is called and the memory in buf
is freed. Is it possible to prevent this? If not, what would be the "proper" way to implement a class like this?