c++ – In a chess simulator, how to efficiently determine checkmate?

I’m working on a small C++ chess simulator game for the first time, and I have a bit of a programming dilemma. I have searched for similar questions on this site and StackOverflow, but can’t find a consensus on what to do here, so hopefully this is an appropriate question for this site.

I’m currently working on implementing check, through a function that starts at the king’s position and checks all knight moves, verticals, horizontals, and diagonals for threatening pieces. If it finds a threatening piece that isn’t blocked by another piece, then the king is considered to be in check and the player must make their next move in a way that gets them out of check. That seems to be the most efficient solution for determining check from the chess-related posts I’ve seen.

However, I’m stuck on how to efficiently implement checkmate. The only logical way I can think of is that once the check flag has been raised, run the check function on every legal follow-up move to see if it results in non-check, and if none of them do, it is checkmate.

Or, to express this in C++ pseudocode:

bool checkForCheckmate() {
  for (allLegalMoves)
  {
    doMoveTemporarily();
    if (!inCheck) {
      return false; // The player can get out of check, so it's not checkmate.
    }
  }
  return true; // If we got here, none of the player's legal moves can get them out of check, so it's checkmate.
}

While it makes sense to me and is logical, that seems extremely inefficient, and this is supposed to be a fairly simple and lightweight application. However, this seems to be the approach suggested by most sources when I look up “how to implement checkmate in a chess game.”

Is there another, potentially more efficient chess algorithm to check if a given arbitrary board arrangement is a checkmate?