C++ Linux 运行时basic_string::_M_construct null 无效错误
C++ Linux basic_string::_M_construct null not valid error during runtime
这在Linux上C++。我在运行时收到错误,并且我已经缩小了此处的代码范围,这是一个自定义对象的构造函数。我所做的是创建一个新线程并将一个函数传递给它。在这个函数中,我像这样调用构造函数:
ColorNinja cn(gameData->difficulty);
gameData
是一个也传递给线程的结构,其中difficulty
是int
成员变量。
我不完全了解错误或导致错误的原因。有人有见识吗?
这是构造函数。如有必要,我可以提供更多代码。
ColorNinja::ColorNinja(int difficulty) {
// create the engine that will generate random numbers
random_device rand;
mt19937 engine(rand());
int randomNumber = 0;
// possible colors that can be present on the randomly-generated game board
vector<string> possibleColors = {"red", "blue", "yellow", "green"};
uniform_int_distribution<int> distribution2(0, possibleColors.size());
// build the game board by choosing and inserting random colors
for (int i = 0; i < 4; i++) {
randomNumber = distribution2(engine);
gameBoard.push_back(possibleColors[randomNumber]);
}
// print the game board
cout << "gameBoard.size(): " << gameBoard.size() << endl;
for (string s : gameBoard) {
cout << s << endl;
}
}
初始化distribution2
时需要使用possibleColors.size()-1
:
std::uniform_int_distribution<int> distribution2(0, possibleColors.size()-1);
std::uniform_int_distribution
的两个构造函数参数是要生成的最小值和最大值。通过使用possibleColors.size()
作为最大值,可以允许生成器返回可能超出数组范围的索引。如果你使用possibleColors.at(randomNumber)
,如果真的发生了,你会得到一个std::out_of_range
错误。 使用possibleColors[randomNumber]
不执行任何边界检查,因此它会很乐意采用无效索引,然后您的代码将具有未定义的行为。 因此,初始化生成器以仅生成有效索引非常重要。
附带说明:由于possibleColors
是一个固定数组,请考虑使用std::array
而不是std::vector
:
#include <array>
std::array<string, 4> possibleColors{"red", "blue", "yellow", "green"};
相关文章:
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 如何在 c++ 中'NULL'字符串
- c++使用foreach使数组为null
- 当使用通配符和null指针调用函数时,对输出的说明
- 当字段可以为null时,如何使用C++接口在Avro中写入数据
- 如何在映射中返回null
- 为什么返回 NULL 不会破坏函数?
- 构造函数中的 QQuickItem 父项 null
- 检查字符串是否"null" C++
- fopen 在 gdb 中返回 NULL
- what(): basic_string::_M_construct null not valid
- 在这个函数中是有缺陷的,因为取消引用 null 是无效的,所以我想更改代码
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 为什么要从main()返回NULL?
- 为什么 nlohmann/json 序列化 "null" 而不是在 double 上"0"?
- 当目标指针不是基类的类型时,为什么允许dynamic_cast为多态类生成 null 指针?
- 是否有通用方法可以找到任何以 null 结尾的字符串的长度?
- 为什么TinyXML2的XMLDocument::FirstChild()函数在尝试解析这个有效的XML文件时返回NULL?
- 使用 curl_easy_cleanup(curl) 时收到未经处理的 NULL 异常
- ClassTemplateSpecializationDecl 的定义数据为 null