views:

81

answers:

1

Somewhere I saw a post about an optimized way of creating a boost shared_ptr so that it allocated the ptr plumbing and the pointee at the same time. I did a SO search but there are a lot of posts on shared_ptr and I could not find it. Can somebody smart please repost it

edit: thanks for answer. extra credit question. Whats the correct (preferred?) idiom for returning a null shared_ptr? ie

FooPtr Func()
{
   if(some_bad_thing)
      return xxx; // null
}

to me

return FooPtr((Foo*)0);

looks kinda klunky

+4  A: 

See boost::make_shared():

Besides convenience and style, such a function is also exception safe and considerably faster because it can use a single allocation for both the object and its corresponding control block, eliminating a significant portion of shared_ptr's construction overhead. This eliminates one of the major efficiency complaints about shared_ptr.

Sean Fausett
[For general information: Note that there's a big potential issue with taking advantage of this: the storage allocated for the object cannot be deallocated until there are no strong or weak references, because the reference count struct is part of the same allocation as the owned object. With an ordinary `shared_ptr` construction, the storage can be deallocated as soon as there are no more strong references. It's just something to keep in mind: if you have really large objects and may have weak references that stick around for a while, it might be an issue.]
James McNellis