Working with Data

Implementing Autosave

How do games typically handle automatic saving? Should we save after every player action?

Abstract art representing computer programming

Autosave systems need to balance data safety with performance. Here's a typical implementation:

Event-Based Saving

Save after significant events rather than every action:

class AutosaveManager {
  std::chrono::steady_clock::time_point
  LastSave;
  bool SignificantChangeOccurred{false};

public:
  void OnPlayerAction(
    const Action& PlayerAction) {
    if (IsSignificantAction(PlayerAction)) {
      SignificantChangeOccurred = true;
      TryAutosave();
    }
  }

  bool IsSignificantAction(
    const Action& PlayerAction
  ) {
    return
      PlayerAction.Type == ActionType::LevelUp ||
      PlayerAction.Type == ActionType::ItemAcquired ||
      PlayerAction.Type == ActionType::QuestComplete;
  }

  void TryAutosave() {
    auto Now = std::chrono::steady_clock::now();
    bool TimeElapsed =
      (Now - LastSave) >
      std::chrono::minutes(5);

    if (SignificantChangeOccurred &&
      TimeElapsed) {
      SaveGame();
      LastSave = Now;
      SignificantChangeOccurred = false;
    }
  }
};

Background Saving

To prevent gameplay interruption, save in a separate thread:

#include <thread>
#include <queue>
#include <mutex>

class BackgroundSaver {
  std::thread SaveThread;
  std::queue<SaveRequest> SaveQueue;
  std::mutex QueueMutex;
  bool Running{true};

public:
  BackgroundSaver() {
    SaveThread = std::thread([this]() {
      while (Running) {
        ProcessSaveQueue();
        std::this_thread::sleep_for(
          std::chrono::milliseconds(100)
        );
      }
    });
  }

  void QueueSave(const GameState& State) {
    std::lock_guard Lock(QueueMutex);
    SaveQueue.push({
      State,
      std::chrono::steady_clock::now()
    });
  }
};

Many games also maintain multiple autosave slots and rotate between them to prevent corruption if a save is interrupted.

The key is finding the right balance between saving frequently enough to prevent significant progress loss while not impacting performance.

Answers to questions are automatically generated and may not have been reviewed.

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 75 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2025 - All Rights Reserved