This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: "Interesting" behavior in std::locale


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.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]