当我运行以下源代码时,在第 3 行出现“Segmentation fault (core dumped)”
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;
如果我将第 2 行替换为
const std::collate<char>* pc = new std::collate_byname<char>("en_US");
我能得到正确的结果。 我认为这两行的结果应该是相同的,它们都是从执行环境中得到的,那么为什么前者会出错呢? 我做错了什么吗?
PS: c++ 编译器是 g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3)。
最佳答案
The reference returned by this function is valid as long as any
std::locale
object exists that implements Facet.
您正在您的代码中创建一个临时的 std::locale
,因此该临时的在表达式的末尾被销毁,并且您留下了一个悬空指针。像这样,它应该可以工作:
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;
关于c++ - std::collate::transform 导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21823822/