Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble switching from vector of dumb pointers to boost::shared_ptr

Alright, this has had me stumped on and off for a couple of months now, so I'll see if anyone else can help with this.

So in my main program I have two kinds of structs (solarBody_t, ship_t) that are both derived from the same base class (physical_t). I make a vector of both objects, since I can't put a solarBody and a ship in the same vector. They are both dumb pointer vectors.
I tried putting both in the same vector, using a vector of boost::shared_ptrs. Now, to my understanding, shared_ptrs should have the same semantics and syntax as dumb pointers (e.g. foobar->mass = 42; should work for both). However, just changing the declaration to a vector of boost::shared_ptr to dumb pointers, it gives me an error when I try and push_back something to the vector of shared_ptrs.

From what I can tell, this should work. The boost docs give the example of

boost::shared_ptr<int> p(new int(2));

which is pretty much what I'm doing.

Has anyone had previous experiences with this? Or want to suggest another way to store everything in a vector?

For more details, here's the gist of it (kind of a contradiction of terms, but I made the pun, so there.)

like image 587
pmelanson Avatar asked Dec 08 '25 13:12

pmelanson


1 Answers

I don't think it'll let you automatically construct a shared_ptr from a bare pointer. push_back is expecting a shared_ptr<foobar_t>, not a bare foobar_t. You should take a look at boost::make_shared and try something like this:

entity_smart.push_back(boost::make_shared<foobar_t>(42));

make_shared has a few advantages: namely, it allocates the pointer control block and the object itself in one allocation and keeps an unmatched new out of your code. It also makes it explicitly clear that you're creating a shared_ptr to an object.

Other than that, yes, the semantics should be basically the same. Keep in mind that shared_ptr may be overkill for what you're doing, though, if you don't actually need to share ownership of the objects.

like image 196
Wyatt Anderson Avatar answered Dec 10 '25 03:12

Wyatt Anderson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!