Boost logo

Boost Users :

Subject: Re: [Boost-users] Usage of Boost.Optional
From: Edward Diener (eldiener_at_[hidden])
Date: 2010-10-24 21:48:47


On 10/24/2010 7:41 PM, John Dlugosz wrote:
> I have a situation where 'optional' is a good fit. However, I can't quite figure out how to use it for what I want. It appears to be geared around passing and returning instances, but I want to use it as a member. Consider:
>
> class C {
> D* d;
> // ... real code has much more stuff, naturally
> public:
> D(params) : d(0)
> {
> // ...
> if (I_ended_up_needing_d) d= new D (blahblah);
> // ...
> }
> ~D() {
> delete d; // harmless if zero
> }
> };
>
>
> There is a single ownership of d by the instance, and it is not polymorphic but an exact type known at compile time. Making it a pointer adds overhead of using the heap, makes it harder to write EH-safe code for the constructor in more realistic situations, and requires adding explicit code to the destructor. Using a smart pointer only adds overhead, might take care of the EH and housekeeping, but still uses the heap.
>
> The 'optional' class provides for in-place storage, which it can use for an initialized instance, or it could be nil. That's exactly what I want. But, how do I tell optional<D> to construct at some point within the 'if' statement of my code? Assigning requires duplicating the object, and this type is not meant to be copied and has copy constructing and assignment disabled.
>
> Based on how the class works, I should be able to say "turn it on, now" and use an in-place factory. But the function to do that is not present in the class.
>
> class C {
> optional<D> d;
> public:
> D(params) : d(boost::none_t)
> {
> if (I_ended_up_needing_d) d.reset (in_place(blahblah));
> }
> };
>
>
> Am I missing something, or is the class missing something?

Just assign your D instance to 'd' when you want to do so.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net