How often have you declared a variable and invented an ungrokkable three-letter name for that variable, just to temporarily hold the result of some API function so that you can check it immediately after the call? Let me guess, you’ve done that thousands of times. And if so then here are happy tidings: you can completely avoid introducing all those helper variables! 🙂
OK, this is a version 2 of my last posting about constructor arguments forwarding in C++98… Anders Dalvander kindly pointed out (without using these words) that my initial motivating example was pretty silly since Boost already offers the functionality that I fronted as desirable, namely, since 2008, the
boost::make_shared function. The original posting is still technically correct, and it’s still about something Practically Very Important™ that Boost apparently does not yet offer, namely reusable C++98-compatible constructor arguments forwarding. But my original posting (1) was sort of lying by omission, by not mentioning
boost::make_shared, and due to that, (2) at least the casual reader would not care to read beyond the introduction! So herewith an updated version, with hopefully no lying by omission, and (cheers!) more examples & discussion! 🙂
Every time you dynamically allocate a new T object and give it to a
> for safekeeping, the
> will dynamically allocate a corresponding reference counter object. But dynamic allocations are usually Very Costly. So wouldn’t it be great if those two allocations could be reduced to a single allocation, a sort of cost-free
Uhm, well, yes? And one way is to specially design your type T to support reference counting and use e.g.
boost::intrusive_ptr (unfortunately not adopted into C++0x). But this is an intrusive solution. And so it is not always applicable, and where it is applicable it may just transfer a runtime efficiency cost to a programmer’s time cost. So on reflection, while for the cases where it can be applied it is perhaps better than
shared_ptr’s extra allocation, it’ not all that great a solution, really.
But wouldn’t it be even greater to have some non-intrusive shared pointer type like
boost::shared_ptr that could manage this for you, a single allocation, without any special support from or requirements on your type T?
That means that you specify your type T constructor arguments to the smart pointer constructor, and let the smart pointer do the allocation. I.e. the smart pointer takes responsibility not only for destruction but also for construction. However, this requires constructor arguments forwarding, which is not supported by C++98.