pointers in structs a memory leak?
I couldn't find any mention of this online... wouldn't putting a pointer in a struct be a bad thing? (at least in the modern object oriented programing) The programmer would inevitably creating a memory leak correct? (unless they, every time they use it, they disassociate the memory every time)
Assuming that th开发者_如何学JAVAe above is correct... is it considered a bad practice to use pointers in structs? - specifically accounting potential memory leaks?Assuming this is about C++, putting a dumb pointer into a struct
is indeed dangerous if this pointer refers to an object (or an array of objects) that is owned by the struct
's instance (that is, the instance is responsible for the proper deletion of the object).
Copying an instance of the struct
means copying all of its members. After that, you end up with several instances of that struct
having pointers to the same object. When all of these instances are about to be deleted, you would have to delete the object referred to by the pointer. However, if one of them is about to be deleted, it is often hard to tell if other instances are still around somewhere.
A way out of this would be reference-counting, done by clever implementing constructors, destructors, and assignment. Fortunately you don't need to implement this yourself, since it's already been done in so-called smart pointer. Either your standard library ships TR1's std::tr1::shared_ptr
or it already comes with C++11's std::shared_ptr
or you can download the boost libraries and use their boost::shared_ptr
.
精彩评论