Subject: Re: undefined behaviour in boost help
From: "Vladimir Marko" <[email-masked]>
Date: 4 Apr 2005 12:16:59 -0400
Newsgroups: comp.lang.c++.moderated

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