Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / C++

assert i NDEBUG: wyłączalne asercje w czasie wykonania

`assert` sprawdza wewnętrzne założenie programu podczas wykonania. Makro `NDEBUG` może wyłączyć to sprawdzenie bez obliczania warunku; nie wpływa na `static_assert`.

Wersja: ISO C++23; implementation support may vary

Składnia

#include <cassert>
assert(condition);

W C++23 assert(condition) z <cassert> to makro funkcyjne, a nie funkcja std::assert. Gdy asercja jest włączona i wykonanie do niej dochodzi, warunek typu skalarnego jest obliczany. Wynik różny od zera oznacza, że program działa dalej. W przeciwnym razie makro wypisuje komunikat diagnostyczny na standardowy strumień błędów i wywołuje std::abort(), kończąc program w sposób nienormalny. Format komunikatu zależy od implementacji.

Jeśli NDEBUG jest zdefiniowane w momencie dołączania <cassert>, assert(condition) rozwija się do ((void)0) i warunek nie jest obliczany. Liczy się samo zdefiniowanie makra: #define NDEBUG 0 też wyłącza asercje. Stan NDEBUG jest sprawdzany przy każdym dołączeniu nagłówka; późniejsza zmiana makra bez ponownego dołączenia nagłówka nie zmienia już ustalonej definicji assert. Nazwa konfiguracji kompilacji, np. Release, sama o tym nie decyduje.

Używaj assert do sprawdzania wewnętrznych niezmienników, nie do walidacji danych wejściowych, kontroli dostępu ani obsługi błędów, które program powinien obsłużyć. Czynności niezbędne do działania programu, takie jak ++count, wykonuj poza asercją. W C++23 makro przyjmuje jeden argument: jeśli wyrażenie zawiera przecinek nieosłonięty nawiasami, ujmij całe wyrażenie w dodatkową parę nawiasów.

static_assert to deklaracja języka, a nie makro. Sprawdza wyrażenie stałe podczas kompilacji; niespełniona asercja statyczna oznacza, że program jest niepoprawny. NDEBUG jej nie wyłącza.

Przykłady

#include <cerrno>
#include <csignal>
#include <cstdio>
#include <cstring>
#include <memory>
#include <string>
#include <sys/wait.h>
#include <unistd.h>

#undef NDEBUG
#include <cassert>

static void check_enabled(int argc)
{
    assert(argc == 1);
}

#define NDEBUG
#include <cassert>

static void check_disabled([[maybe_unused]] int argc)
{
    assert(argc == 1);
}

static constexpr char next_statement[] = "Reached the next statement.";

static bool read_output(std::FILE* file, std::string& text)
{
    if (std::fseek(file, 0, SEEK_SET) != 0)
        return false;
    char buffer[256];
    while (const auto n = std::fread(buffer, 1, sizeof buffer, file))
        text.append(buffer, n);
    return !std::ferror(file);
}

static bool run(const char* executable, const char* name, const char* extra,
                bool should_abort, std::string& transcript)
{
    using File = std::unique_ptr<std::FILE, decltype(&std::fclose)>;
    File out(std::tmpfile(), &std::fclose);
    File err(std::tmpfile(), &std::fclose);
    if (!out || !err)
        return false;

    const pid_t child = fork();
    if (child < 0)
        return false;
    if (child == 0) {
        if (dup2(fileno(out.get()), STDOUT_FILENO) < 0 ||
            dup2(fileno(err.get()), STDERR_FILENO) < 0)
            _exit(126);
        // Re-execute this binary with the displayed name as argv[0].
        if (extra)
            execlp(executable, name, extra, static_cast<char*>(nullptr));
        else
            execlp(executable, name, static_cast<char*>(nullptr));
        _exit(127);
    }

    int status;
    pid_t waited;
    do {
        waited = waitpid(child, &status, 0);
    } while (waited < 0 && errno == EINTR);
    if (waited != child)
        return false;

    std::string stdout_text, stderr_text;
    if (!read_output(out.get(), stdout_text) || !read_output(err.get(), stderr_text))
        return false;
    if (should_abort) {
        if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGABRT ||
            !stdout_text.empty() || stderr_text.empty())
            return false;
    } else if (!WIFEXITED(status) || WEXITSTATUS(status) != 0 ||
               stdout_text != std::string(next_statement) + '\n' || !stderr_text.empty()) {
        return false;
    }

    transcript += name;
    if (extra) {
        transcript += ' ';
        transcript += extra;
    }
    transcript += "\n  stdout: ";
    if (should_abort) {
        transcript += "empty\n  stderr: assertion diagnostic (exact text varies)\n"
                      "  Abnormal termination via std::abort().\n";
    } else {
        transcript += stdout_text;
    }
    return true;
}

int main(int argc, char** argv)
{
    if (std::strcmp(argv[0], "./assert-on") == 0) {
        check_enabled(argc);
    } else if (std::strcmp(argv[0], "./assert-off") == 0) {
        check_disabled(argc);
    } else {
        std::string transcript = "Expected results:\n";
        if (!run(argv[0], "./assert-on", nullptr, false, transcript) ||
            !run(argv[0], "./assert-on", "extra", true, transcript) ||
            !run(argv[0], "./assert-off", "extra", false, transcript)) {
            std::fputs("Unexpected result from an assertion test run.\n", stderr);
            return 1;
        }
        transcript.pop_back();
        return std::fputs(transcript.c_str(), stdout) == EOF ? 1 : 0;
    }
    std::puts(next_statement);
}

Wynik

Expected results:
./assert-on
  stdout: Reached the next statement.
./assert-on extra
  stdout: empty
  stderr: assertion diagnostic (exact text varies)
  Abnormal termination via std::abort().
./assert-off extra
  stdout: Reached the next statement.

Wersja z włączonymi asercjami wypisuje `Reached the next statement.` bez dodatkowego argumentu, ale z argumentem `extra` wypisuje komunikat diagnostyczny na standardowy strumień błędów i przerywa działanie przed wypisaniem tego wiersza. Wersja z `NDEBUG` wypisuje ten wiersz również z `extra`, ponieważ nie oblicza warunku `argc == 1`.

Powiązane lekcje

  • C++ · Lekcja 49 · Średniozaawansowany · Wersja: 2

Źródła