locale in Objective-C++ is confusing

hi all,

i wrote my tool app using ObjC++, find some problems while messing with "locale". here's the problems:

  1. I invoke a C++ function,
std::string ws2s(const std::wstring& ws)

{

    if (ws.empty())

        return "";

    NSLog(@"%s %s", setlocale(LC_ALL, NULL), std::locale().name().c_str());
...

output is "C C", and i try to set locale to "zh_CN.UTF8", but it's still "C".

another is an Objc Class Method

+ (NSString*)getNSStrFromWCharStr:(const wchar_t*)wcstr {
    if (wcstr == NULL) return nil;

    
    char *curLocale = setlocale(LC_ALL, NULL);
...

this time, curLocale is the same as system default ——"zh_CN.UTF8"

  1. I try to set locale in main function, first one succeed, second made process crash.
        setlocale(LC_ALL, "zh_CN.UTF-8");
            std::locale::global(std::locale("zh_CN.UTF8"));

crash info:libc++abi: terminating due to uncaught exception of type std::runtime_error: collate_byname<char>::collate_byname failed to construct for zh_CN.UTF8

after all this, it's OK to handle CN character with C and objc, but it's not OK with C++. and I'm confused, I don't know much about 'locale'. I thought it was a per-process setting, now it seems to be a per-language setting...

OS version: macOS 14.4, system default locale is "zh_CN.UTF8".

What's the reason for setting locale? Unless you are using some old C standard library or posix API, there is usually no reason to change it.

locale in Objective-C++ is confusing
 
 
Q