Boost smart pointers and hash_maps

Started by
3 comments, last by Syranide 18 years, 7 months ago
Ok, I just started fiddeling some with the smart pointers in boost but I'm unable to figure what pointer is useful for what. I've looked at some of their samples and none really makes me any wiser... as I don't see the meaning of what they do. I tried their shared_ptr example and sure it works, but, I cannot assign elements to the hash_map if it would be out of the local scope (since as soon as the local scope ends, the inserted element will free itself)... How does one usually accomplish this kind of behaviour? That is, common hash_map use, for instance, have a class variable of the type hash_map... and then being able to add elements to it using the functions implemented in my class, without having to do all the tedious cleaning up when removing elements from it. Thanks in advance.


Advertisement
Quote:Original post by Syranide
I tried their shared_ptr example and sure it works, but, I cannot assign elements to the hash_map if it would be out of the local scope (since as soon as the local scope ends, the inserted element will free itself)...

If you've inserted the element into the hash map, then there will be another reference to the object, and the object won't be destroyed when the first reference goes out of scope.
Yeah I figured that too...

Oh, no... darn!
A very stupid mistake at my end, I mistakedly forgot to pass the vector/set as a pointer, and instead got a clone, which was simply freed when the local scope ended. (can't do anything but to blame myself for the dumb rewrite of the code)

So, it works perfectly... err, thanks I'll guess ;)

While still on it... what is major difference between the smart pointers?
Is shared_ptr the way to go in my scenario?

Regards Andreas


the shared_ptr is useful for multiple pointers pointing to the same object. shared_array is the same thing, but for arrays. scoped_ptr and scoped_array are good for inside local functions when you want a pointer, and won't need it outside of that function (you want it to be destroyed at the end of the function). weak_ptr "observes" an object owned by a shared_ptr and can break circular references. intrusive_ptr is good for working with APIs (like DirectX) that keep their own referance count. You can tell the intrusive_ptr how to delete the pointer (in the DirectX case, just call Release). intrusive_ptr is also lightweight and is the same size as a raw pointer as long as you implement the reference counting yourself inside your class. The shared_ptr, shared_array, and weak_ptr can be used in stl containers.

Tutorial
Spot on perfect!
Huge thanks.


This topic is closed to new replies.

Advertisement