|
Boost Users : |
Subject: [Boost-users] Usage of Boost.Optional
From: John Dlugosz (JDlugosz_at_[hidden])
Date: 2010-10-24 19:41:09
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?
I'm using Boost 1.43 in the project, and basing the above on the documentation for that version. The 'news' for 1.44 does not list Optional as having changed.
Thanks,
--John
(sorry about the corporate footer)
TradeStation Group, Inc. is a publicly-traded holding company (NASDAQ GS: TRAD) of three operating subsidiaries, TradeStation Securities, Inc. (Member NYSE, FINRA, SIPC and NFA), TradeStation Technologies, Inc., a trading software and subscription company, and TradeStation Europe Limited, a United Kingdom, FSA-authorized introducing brokerage firm. None of these companies provides trading or investment advice, recommendations or endorsements of any kind. The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon, this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from any computer.
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