Pregunta

When I run the following source code, got "Segmentation fault (core dumped)" at line#3

char s[] = "helloworld";
const std::collate<char>* pc = &std::use_facet<std::collate<char> >(std::locale("en_US"));
std::string str = pc->transform(s, s + std::strlen(s));
std::cout << str.length() << "," << str << std::endl;

If I replace the line#2 with

const std::collate<char>* pc = new std::collate_byname<char>("en_US");

I can get the correct result. I think this two lines' result should be same, they all get a collate from the execution environment, so why the former got a fault? Did I do something wrong?

PS: The c++ compiler is g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3).

¿Fue útil?

Solución

Reading the docs of use_facet:

The reference returned by this function is valid as long as any std::locale object exists that implements Facet.

You're creating a temporary std::locale in your code, so that temporary is destroyed at the end of the expression, and you're left with a dangling pointer. Like this, it should work:

char s[] = "helloworld";
std::locale en_US("en_US");
const std::collate<char>* pc = &std::use_facet<std::collate<char> >(en_US);
std::string str = pc->transform(s, s + std::strlen(s));
std::cout << str.length() << "," << str << std::endl;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top