Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2005-04-04 12:08:26


Is the maintainer of this code listening?


attached mail follows:


Sandor wrote:
> I found the following code example in the Boost library documentation
at
> http://boost.org/libs/utility/in_place_factories.html
>
> struct C
> {
> C() : contained_(0) {}
> C ( X const& v ) : contained_ ( new X(v) ) {}
>
> template<class InPlaceFactory>
> C ( InPlaceFactory const& aFactoty )
> :
> contained_ ( uninitialized_storage() )
> {
> aFactory.template apply<X>(contained_);
> }
>
> ~C() { delete contained_ ; }
>
> X* uninitialized_storage() { return static_cast<X*>(new
> char[sizeof(X)]) ; }
>
> X* contained_ ;
> } ;
>
> void foo()
> {
> C c( in_place(123,"hello" ) ;
> }
>
> I believe that the "delete contained_" expression causes undefined
> behaviour, because the contained_ pointer sometimes points to an area

> allocated with new[]. Such areas must be deleted with delete[]. Am I
> correct? (It seems quite unfortunate to increase confusion with
putting
> undefined-behaviour code into the docs.)

Yes. And even on architectures where this could work, what if
X has a class specific allocation and deallocation function?
And what about the exception safety? The example is simply an
example of bad programming practice. A good example would have
a container with an allocator and the complete separation of
allocation/deallocation and construction/destruction would do
the trick.

Regards,
Vladimir Marko

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated. First time posters: Do this! ]


-- 
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