Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent anyone from stealing my shared_ptr?

So, I use boost::shared_ptr for all the various reference-counting benefits it provides -- reference counting for starters, obviously, but also the ability to copy, assign, and therefore store in STL Containers.

The problem is, if I pass it to just one "malicious" function or object, the object can save the ptr and then I'll never be able to de-allocate it without the foreign function or object nicely relinquishing its ownership.

Ultimately, I try to keep object ownership explicit. I accomplish this by having the owner keep the only shared_ptr to the object, and "guest" objects only store weak_ptrs to the object.

I really don't want the "shared" part of shared_ptr, but I'm required to use shared_ptr in order to make weak_ptrs. I want to use scoped_ptr, but it's extremely limited since you can't copy it. You can't store it in a container, you can't lend out weak_ptrs from it, and you can't transfer ownership to a new manager.

What's the solution?

like image 232
Kyle Avatar asked Apr 22 '10 02:04

Kyle


1 Answers

Make it private and provide a facade to do whatever operations needed. Nobody ever sees the pointer. I guess that at that point you would not even need a shared_ptr.

like image 140
Romain Hippeau Avatar answered Sep 20 '22 02:09

Romain Hippeau