Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2005-07-11 14:09:21


Andrey Melnikov <melnikov_at_[hidden]> writes:

> Each of them includes some extra operations which aren't necessary.
> Version 1 is terrible, version 2 uses an extra default construction,
> version 3 uses an extra memory allocation.
>
> Here is a better version:
>
> void foo( std::string * bar )
> {
> new (bar) std::string("bar");
> }
> ...
> char bar_placeholder[sizeof(std::string];
> std::string *bar = reinterpret_cast<std::string*>(bar_placeholder);

reinterpret_cast is nonportable.

> foo(bar);
> ...
> bar->~std::string();
>
> It uses just one constructor call, no extra default constructors and no
> dynamic memory allocation. So far after reading the documentation, it
> seems to me that boost::optional provides a nice encapsuation for this
> bulk of code.

Or just an opportunity for premature optimization. On a compiler
supporting RVO and other kinds of copy elision, the "terrible" version
could be just as efficient, or more so.

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk