Should I de-allocate inside the class, or outside?

Started by
3 comments, last by Raeldor 18 years, 7 months ago
I have a mesh class that holds pointers to arrays of vertices, uv's etc. I want to be able to build the mesh manually, so create my own arrays and assign to the mesh, aswell as having a LoadFromFile function that loads a mesh from disk (thus creating the vertex array inside the class). How do I know if the vertices have been allocated externally or from the load mesh? Is it good practice to de-allocate anyway even if they have been created outside the class, or should the de-allocation always be done by the same class as did the allocation? Thanks [Edited by - Raeldor on September 5, 2005 10:09:11 PM]
Advertisement
The vertices are a fundamental part of the mesh, thus the mesh should be the one to delete them. Just think of everything in terms of who owns it. Every bit of memory must be owned, and the owner must always deallocate or hand off ownership.
A reference-counted pointer (boost::shared_ptr?) is a good solution. The data is not deallocated until everyone has released it. So the code that allocated it can release it whenever it wants, and your mesh class can release it whenever it wants. When you load the mesh from a file, you still use the ref-counted pointer (even though there is only one reference). That way, the mesh deallocates the data is the same way either way.
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!
Whatever "owns" the data is responsible for destroying it. It is very bad to have ownership ambiguity.

The mesh should own its vertices and make copies of data passed into it externally. Either meshs own themselves and use refernce counting (not what I'd recommend), or a resource manager owns them (and thus is responsible for destroying them). For example, the resource manager could be used to destroy all the meshes when loading a new level or destroying all the meshes created since a certain point in time.

Actual game objects only reference mesh data, they never own them.
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Quote:Original post by Shannon Barber
The mesh should own its vertices and make copies of data passed into it externally. Either meshs own themselves and use refernce counting (not what I'd recommend), or a resource manager owns them (and thus is responsible for destroying them). For example, the resource manager could be used to destroy all the meshes when loading a new level or destroying all the meshes created since a certain point in time.


Hi, thanks for your reply. To make copies of the data seems like a huge overhead. Why do you see this as a preferred solution to smart pointers? Are there problems with smart pointers I am unaware of?

Thanks

This topic is closed to new replies.

Advertisement