Boost logo

Boost :

From: Anthony Williams (anthony_w.geo_at_[hidden])
Date: 2007-04-05 06:30:52


Iulian M <eti_at_[hidden]> writes:

> On Thursday 05 April 2007, Kevin Yuan wrote:
>> > 2007/4/4, Martin Bonner <Martin.Bonner_at_[hidden]>:
>> > Static variable in an inline function.
>>
>
> Am I missing something or static variables in inline functions are considered
> BAD PRACTICE?
>
>> Yes, I agree. Something like:
>>
>> // st.h
>> class st
>> {
>> private:
>> st(){}
>> public:
>> static st* get_instance()
>> {
>> static st* inst = new st;
>> return inst;
>> }
>> };
>
> IIRC if get_instance() will be inlined and 2 translation units will have their
> own copy of get_instance() then there will be two st instances in the finall
> app... witch in case of a singleton is BAD.
>
> ps: i only had 2 zips of coffee so i might be missing something ...

Have another cup of coffee then, because you are missing something.

The compiler is required to ensure that there is only one copy of statics
declared in inline functions, even if that function is defined in more than
one translation unit, because otherwise you get precisely the problem you
describe.

Anthony

-- 
Anthony Williams
Just Software Solutions Ltd - http://www.justsoftwaresolutions.co.uk
Registered in England, Company Number 5478976.
Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk