How to manage resources that cannot be deep-copied in C++

Viewed 138

I am creating a class that manages a resource that should not be "deep copied", that is, there can only ever be one instance of the underlying resource, even if multiple objects have access this same resource.

However, allowing multiple objects to access this resource is also dangerous, as one object could go out of scope, and self-destruct, which will also destroy the resource. In this case, is it reasonable to only define a move constructor (without allowing for shallow copies)? Or is there some way to support shallow copies, so that multiple objects can reference the same resource, but the resource will not be destroyed if at least one object still has access to the resource?

For context, the resource being managed is an OpenGL shader, and each object has the ID of this shader as one of it's members, which it uses to tell OpenGL to delete the shader when necessary.

1 Answers

I think that you are looking for std::shared_ptr or parallel solution; std::shared_ptr is used to share pointers to a single object, which is destroyed only after all of the shared pointers are cleared. Thus, while we still have a reference to the object, it remains valid.

Even if you are not looking to use shared_ptr, the idea behind it is to use a reference counter, which is shared by all objects that refer to the same resource - each time you call a constructor/copy constructor/copy-assignment, you increase the shared counter by 1, and in the destructor, you decrease it by 1, and if (and only if) it reaches 0 then you release the underlying resource.

Also, for completeness of the answer, I should add that for std::shared_ptr, there is in addition std::weak_ptr, which denotes access without shared ownership - it allows one to access a resource held by a std::shared_ptr while it is alive, but can be reset automatically if all of the std::shared_ptr that refer to the resource are destroyed. It is rare to see usage of it, but it is possible to use it, nevertheless.

Related