How to check if construction of a new codecvt_byname succeeded

566 views Asked by At

Is there a standard way to check whether construction of a new std::codecvt_byname succeeded?

I was experimenting with the following program:

// cl /nologo /Fetest_codecvt_byname.exe /EHsc test_codecvt_byname.cpp && test_codecvt_byname
// g++ -o test_codecvt_byname test_codecvt_byname.cpp && test_codecvt_byname

#include <cstdlib>
#include <iostream>
#include <locale>
#include <new>
#include <stdexcept>

int main()
{
    try {
        new std::codecvt_byname<wchar_t, char, mbstate_t>(".nonsense");
    } catch (const std::exception& ex) {
        std::cerr << "Error: " << ex.what() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

libstdc++ on Windows apparently throws a std::runtime_error object if the named locale is unsupported. Microsoft Visual C++'s STL implementation, however, does not throw an exception.

Not knowing which C++ compiler will compile the code, how do I check whether construction of the new std::codecvt_byname succeeded? Alternatively, is there a way to check whether construction will be successful assuming no out-of-memory scenario?

1

There are 1 answers

0
Daniel Trebbien On BEST ANSWER

Section [22.3.1.1.2], Class locale::facet, of the C++11 FDIS states:

For some standard facets a standard "..._byname" class, derived from it, implements the virtual function semantics equivalent to that facet of the locale constructed by locale(const char*) with the same name.

The Standard unfortunately does not require an exception to be thrown by the std::codecvt_byname constructor if the named locale is invalid, as does the explicit std::locale constructor locale(const char*). However, a work-around is to attempt to construct the locale and use_facet the codecvt facet instead of attempting to use std::codecvt_byname.