This is the mail archive of the
libstdc++@gcc.gnu.org
mailing list for the libstdc++ project.
Re: "Interesting" behavior in std::locale
- From: Jonathan Wakely <jwakely at redhat dot com>
- To: James Benze <benzejaa at gmail dot com>
- Cc: libstdc++ at gcc dot gnu dot org
- Date: Fri, 31 Oct 2014 18:35:57 +0000
- Subject: Re: "Interesting" behavior in std::locale
- Authentication-results: sourceware.org; auth=none
- References: <CAFCb1eYNzFi3_1sCfirFWRFTezJv4VWURsOFPHrh-R0QLJ+pbQ at mail dot gmail dot com>
On 31/10/14 12:07 -0400, James Benze wrote:
Hey all:
I found some code in libstdc++ that, while I understand what it does,
I'm not understand why it's programmed the way it is, and I was hoping
someone could shed some light on the behavior...I was hoping someone
would be bored at work today and wouldn't mind spending the time to
satisfy my curiosity.
The function is std::locale::classic() (in locale_init.cc:256). It
seems to me to be a singleton pattern, but implemented in a strange
way. First it initializes _S_classic, using a normal singleton
initialization pattern. No big deal there. Then, it uses placement
new to create the new c_locale object and then return it. Every time.
So my question is, why wasn't this programmed with an if check to see
if the singleton is already initialized? I made a quick test program:
//with-if.cpp
#include<locale>
std::locale::_Impl* _S_classic;
typedef char fake_locale[sizeof(std::locale)]
__attribute__ ((aligned(__alignof__(std::locale))));
fake_locale c_locale;
std::locale * global = NULL;
int main()
{
if(!global)
*(new (&c_locale) std::locale(_S_classic));
return 0;
}
I don't know the reason, but you'd need more than just an 'if' as
presumably you'd also want to set 'global' to be non-null after the
first call, which would need to be synchronized to avoid data races.