C++ Linux 运行时basic_string::_M_construct null 无效错误

C++ Linux basic_string::_M_construct null not valid error during runtime

本文关键字:construct null 错误 无效 string Linux 运行时 basic C++      更新时间:2023-10-16

这在Linux上C++。我在运行时收到错误,并且我已经缩小了此处的代码范围,这是一个自定义对象的构造函数。我所做的是创建一个新线程并将一个函数传递给它。在这个函数中,我像这样调用构造函数:

ColorNinja cn(gameData->difficulty);

gameData是一个也传递给线程的结构,其中difficultyint成员变量。

我不完全了解错误或导致错误的原因。有人有见识吗?

这是构造函数。如有必要,我可以提供更多代码。

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"};