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

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

初始化时需要使用possibleColors.size()-1 distribution2:

std::uniform_int_distribution<int> distribution2(0, possibleColors.size()-1);

std::uniform_int_distribution 的两个构造函数参数是要生成的 minimummaximum 值。通过使用 possibleColors.size() 作为最大值,您允许生成器 return 一个可能超出数组范围的索引。如果您使用了 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"};