🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c++
Article #3849

Re: initialization of nonlocal static objects

#3849
From: Wil Evers
Date: Thu, 28 Mar 1996 16:20
57 lines
2640 bytes
In article <KANZE.96Mar27134634@gabi.gabi-soft.fr> kanze@gabi-soft.fr (J.
Kanze) writes:
 
>     class X
>     {
>     public :
>         enum DontInit { dontInit } ;
>                         X( DontInit )   {}
>                         X() : i( 5 )    {}
>     private :
>         int             i ;
>     } ;
> 
> Objects to be initialized by the nifty_counter would be defined thus:
> 
>     X               obj( X::dontInit ) ;
> 
> Nifty counter then becomes:
> 
>     class NiftyCounter
>     {
>         static int          cnt ;
>     public :
>                             NiftyCounter()
>         {
>             if ( cnt == 0 )
>                 new( &obj ) X ;
>             cnt ++ ;
>         }
>     } ;
> 
> (Note that for NiftyCounter to work, it is absolutely essential that the
> definition of the object invoke a no-op constructor, since the object
> may in fact already be constructed.)
> 
> As you can see, this works equally well for const objects.

I don't think so. For this to work on a const object, you would at least have
to cast away its constness - after all, the standard placement new operator
takes a void * as its second argument, not a const void *.

In my opinion, the `dummy constructor' technique is fundamentally bad. It
requires that all base classes and member variables have dummy constructors
too, so it is not always applicable.

When I use the nifty counter idiom, I normally construct the global
object in a suitably aligned raw memory buffer (a character array).
Users access the constructed object through a properly typed global
reference pointing to the raw memory buffer.

- Wil
---
[ comp.std.c++ is moderated.  To submit articles: try just posting with      ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu         ]
[ FAQ:      http://reality.sgi.com/employees/austern_mti/std-c++/faq.html    ]
[ Policy:   http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu                             ]
Technical Details
Message-ID: <009A0041E919D6E0.3D60EEDA@ittpub.nl>
Path: arc1-ca.pugleaf.net!in2.uu.net!bounce-back

Show Full Headers
Complete Article Headers
From: "Wil Evers" <wil@ittpub.nl>
Message-ID: <009A0041E919D6E0.3D60EEDA@ittpub.nl>
X-Original-Date: Thu, 28 Mar 96 15:15:49 WET
Path: arc1-ca.pugleaf.net!in2.uu.net!bounce-back
Date: 28 Mar 96 16:20:31 GMT
Approved: fjh@cs.mu.oz.au
Organization: -
Newsgroups: comp.std.c++
Return-Path: <daemon@meeker.UCAR.EDU>
Subject: Re: initialization of nonlocal static objects
X-Vms-Mail-To: IN%"std-c++@ncar.ucar.edu"
X-Auth: PGPMoose V1.1 PGP comp.std.c++
 iQBFAgUBMVq8fuEDnX0m9pzZAQGFRwGAm7rpieiXNI4SLkXWFn6iBHvrBC8i1xb1
 lOnmxa/D0Ruym75qXGUN95ZBF4UACjsc
 =O64g