1818#include " LocaleHelper.h"
1919#include " System.h"
2020#include < boost/filesystem/path.hpp>
21+ #include < boost/optional/optional.hpp>
2122#include < boost/predef/os.h>
2223#include < iostream>
2324#if BOOST_OS_WINDOWS
3132namespace bfs = boost::filesystem;
3233
3334namespace {
35+ class LocaleResetter
36+ {
37+ boost::optional<std::locale> originalLocale;
38+
39+ public:
40+ ~LocaleResetter ()
41+ {
42+ if (originalLocale)
43+ {
44+ try
45+ {
46+ // Reset locale back to default to avoid memory leaks
47+ std::locale::global (*originalLocale);
48+ } catch (...)
49+ {} // Ignore any error
50+ }
51+ }
52+
53+ std::locale changeGlobalLocale (std::locale locale)
54+ {
55+ std::locale oldLocale = std::locale::global (locale);
56+ if (!originalLocale)
57+ originalLocale = oldLocale;
58+ return locale;
59+ }
60+ };
3461std::locale getBfsLocale ()
3562{
3663 std::locale result;
@@ -91,6 +118,7 @@ const std::locale& LocaleHelper::getBfsDefaultLocale()
91118
92119bool LocaleHelper::init ()
93120{
121+ static LocaleResetter localeResetter;
94122 // Check and set locale (avoids errors caused by invalid locales later like #420)
95123 try
96124 {
@@ -100,7 +128,7 @@ bool LocaleHelper::init()
100128 // So don't rely on string conversions to yield identical results on all systems as locale settings can be
101129 // changed!
102130 std::locale newLocale = createUtf8Locale ();
103- std::locale::global (newLocale);
131+ localeResetter. changeGlobalLocale (newLocale);
104132 // Use also the encoding (mostly UTF8) for bfs paths: http://stackoverflow.com/questions/23393870
105133 bfs::path::imbue (newLocale);
106134 } catch (std::exception& e)
0 commit comments