0

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?

wispi
  • 431
  • 3
  • 14
  • 1
    The issue is that `func()` returns a temporary object that has to be destructed, but your code is violating the [Rule of 3/5/0](https://en.cppreference.com/w/cpp/language/rule_of_three). Implementing proper copy/move constructors and copy/move assignment operators would help mitigate this issue. But really, this is the kind of situation that smart pointers like `std::unique_ptr` and `std::shared_ptr` were designed to handle. – Remy Lebeau Sep 28 '20 at 03:47
  • If you solve the problem of [object slicing](https://stackoverflow.com/questions/274626/what-is-object-slicing), your current question might be resolved in the process. – JaMiT Sep 28 '20 at 04:04

0 Answers0