Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2004-07-02 08:05:55


Daryle Walker <darylew_at_[hidden]> writes:

> On 7/1/04 8:48 AM, "David Abrahams" <dave_at_[hidden]> wrote:
>
>> Daniel Frey <daniel.frey_at_[hidden]> writes:
> [SNIP]
>>> I thus wrote the following small helper:
>>>
>>> template< typename T > void reset( T& t )
>>> {
>>> T().swap( t );
>>> }
>>>
>>> Would this make a good addition to boost.utility? Any comments welcome...
>>
>> Not unless you make it generic:
>>
>> template< typename T > void reset( T& t )
>> {
>> using std::swap;
>> T x;
>> swap(x, t);
>> }
>
> Wouldn't that lead to undefined behavior as-is? There's a dirty little
> secret in C++ that unmentioned construction is _not_ the same as default
> construction for most types!

Uh, right. Not so secret actually; that's why we have
value_inititalized:

   #include <boost/utility/value_init.hpp>

   template< typename T > void reset( T& t )
   {
     using std::swap;
     swap(value_inititalized<T>().data(), t);
   }

This will be more efficient than your rewrite.

> For most "T", including POD types, you'll give "x" a random bunch of
> bits

Not most "T"; just for PODs.

> , which cannot be a source of an assignment (only an assignment
> destination).
>
> Unmentioned construction implies default construction only if "T" is:
> 1. A class type with a default constructor explicitly written
> 2. A class type that gets an automatic default constructor because it
> has a base or member on this list
> 3. An array of a type on this list
>
> I think that any other type (built-ins, enums, POD structs) needs the
> explicit default constructor sequence:
>
> template < typename T >
> void reset( T & t )
> {
> using std::swap;
> T x = T();
> swap( x, t );
> }
>
> [I'm not sure that any books or, worse, the standard, explicitly mention
> this.]

They do. See the bottom of http://tinyurl.com/26mpo

-- 
Dave Abrahams
Boost Consulting
http://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