c++ - stof()/stoi() 与取消引用类型双关指针将打破严格别名规则

标签 c++ casting stl std

我有自己的类型

namespace FaF
{
    // Allocator is my own Memory Allocator for STL
    using string = std::basic_string<char, std::char_traits<char>, Allocator<char>>;
}

FaF::string number("1234");
stoi( (const std::string &) number);  <-- error

在使用 -Wall -Werror -Wextra 开关运行 gcc 时,使用 stoi(number) 又名 FaF::string& 会导致此错误:

error: dereferencing type-punned pointer will break strict-aliasing rules [-Werror=strict-aliasing]

我尝试了很多 Actor ,但没有任何帮助。 std::stringFaF::string 或多或少是与内存分配器不同的相同类型。

我的问题:如何使用 stoi()/stof() 函数解决此问题?

更新:: 是的,当然,我可以使用 atoi( number.c_str() ) 但我想了解这里的问题。

最佳答案

这是 sto* 函数类的一个不幸的问题;它们std::string一起使用。尽管他们不关心你使用什么分配器,但这仍然是类型的一部分,所以它对 C++ 仍然很重要。您也不能假装使用不同分配器的 basic_stringstd::string

直到 C++17 solves this problem (kinda) ,您必须手动处理它:

stoi({number.data(), number.size()});

关于c++ - stof()/stoi() 与取消引用类型双关指针将打破严格别名规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38000552/

相关文章:

c++ - 自定义 STL 迭代器类

python - 使用 C/API 和 C++ 类编写 Python 模块

c++ - 为两个类之间具有循环依赖关系定义重载转换运算符

c# - 通用列表<T> 作为 IEnumerable<object>

c++ - 用于排序的多态STL比较函数(class cmp class, class cmp int)

c++ - 最快的 c++/STL 算法在成对的集合中查找字符串

java - 通过 JNI 将 float[][] 传递给 C++ 的最简单方法

java - 我如何处理 JNA 中的不透明指针?

c++ - OpenCv IP 摄像机连接

c++ - 将 ifstream 转换为 bool 和使用 ifstream::is_open() 之间的区别