
David Abrahams wrote:
Andrey Melnikov <melnikov@simplexsoft.com> writes:
char bar_placeholder[sizeof(std::string]; std::string *bar = reinterpret_cast<std::string*>(bar_placeholder);
reinterpret_cast is nonportable.
Why? I don't see any reasons why reinterpert_cast from char [] to std::string * could be nonportable. The only thing I see is that it isn't supported by some compilers. Anyways, it was just an example. Don't judge me too strictly.
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.
I don't think that "don't give opportunities for premature optimization" can be a design goal :) Don't think about this idea just as about an optimization trick. It doesn't require an object to have a default or a copy constructor. It do relax container requirements for stored types. It is useful *sometimes*. And why premature? I didn't recommend to use this code everywhere instead of returning values from functions. Did you miss a paragraph? :) I explicitly stated: ...*In some circumstances* default construction, dynamic memory and copying *can* be computationally too expensive or not available at all... Maybe I should have used "may" there. I definitely need to improve my English skills.
On a compiler supporting RVO and other kinds of copy elision, the "terrible" version could be just as efficient, or more so.
It could of course. But SOMETIMES it doesn't help. I can't imagine how a compiler can avoid calling a non-trivial copy constructor like in case of std::string. Don't forget that such a copy operation includes memory reallocation, which is much more expensive than just a memcpy() operation. Andrey