From: Vesa Karvonen (vesa.karvonen_at_[hidden])
Date: 2001-08-29 13:06:48
From: "Rainer Deyke" <root_at_[hidden]>
> It seems to me that 'optional<T>' is in many ways similar to
> - Both are either null or contain a single object of type 'T'.
> - Both are conceptually pointers to the contained object.
> - 'scoped_ptr<T>' can contain an object of a derived type; 'optional<T>'
> - 'scoped_ptr<T>' keeps the contained object on the heap; 'optional<T>'
> keeps it stores it directly.
> - 'scoped_ptr<T>' is initialized with an object that is already created on
> the heap. This does not make sense for 'optional<T>'.
There are a couple of major difference that you omitted:
- 'scoped_ptr<>' objects can not be returned from a function; 'optional<>'
- 'scoped_ptr<>' objects can not be copied; 'optional<>' can.
> Given those similarities, I think it makes sense for the interface of
> 'optional<T>' to resemble the interface of 'scoped_ptr<T>' as closely as
> possible. If a user of 'optional<T>' later needs to be able to contain
> objects of derived types, switching to 'scoped_ptr<T>' should take a minimal
> amount of effort. The same applies when a user of 'scoped_ptr<T>' who does
> not need to contain objects of derived types and wants the greater
> performance of 'optional<T>'.
Under the current design of scoped_ptr<>, I do not find it likely that a user
would convert a design from optional<> to scoped_ptr<> or vice versa. However,
shared_ptr<> is another story. See the following table:
| morphology | semantic
optional<> | monomorphic | value
shared_ptr<> | polymorphic | reference
My impression could be wrong, but it seems to me that optional<> is mostly
intended for returning values from a function. However, I think that
optional<> is also useful for other things. In particular, it could be useful
for optimization or simplification of optimized logic, because it allows
omitting potentially expensive initialization of an object.
... logic which may initialize x or not ...
... logic which depends on x ...
I think that I have seen the above kind of pattern many times in my coding,
although I believe I have often refactored the code to avoid the pattern.
Basically, optional<> seems like an intentional and type safe way to say that
something may not be needed and may be left uninitialized. Of course, in many
cases, it may be possible to simplify the logic in some other way, avoiding
the need for optional<>.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk