Baza znanjaIzpitno središče
SLSlovenščina
Izberi jezik13

CKTIS / C++

assert in NDEBUG: izklopljiva preverjanja med izvajanjem

`assert` med izvajanjem preveri notranjo predpostavko programa. Z definicijo `NDEBUG` je mogoče preverjanje izklopiti, ne da bi se pogoj ovrednotil. To ne vpliva na `static_assert`.

Različica: ISO C++23; implementation support may vary

Sintaksa

#include <cassert>
assert(condition);

V C++23 je assert(condition) iz <cassert> funkcijski makro, ne funkcija z imenom std::assert. Če je preverjanje omogočeno in ga izvajanje doseže, se ovrednoti pogoj skalarnega tipa. Če rezultat ni enak nič, se izvajanje nadaljuje. Sicer makro zapiše diagnostično sporočilo na standardni tok za napake in pokliče std::abort(), s čimer se program nenormalno konča. Obliko sporočila določa implementacija.

Če je ob vključitvi <cassert> makro NDEBUG definiran, se assert(condition) razširi v ((void)0) in pogoj se ne ovrednoti. Pomemben je le obstoj definicije: tudi #define NDEBUG 0 izklopi preverjanje trditev. Ob vsaki vključitvi glave se upošteva trenutno stanje makra NDEBUG. Poznejša sprememba brez ponovne vključitve glave ne spremeni obstoječe definicije assert. Ime konfiguracije, na primer Release, samo po sebi o tem ne odloča.

Uporabi assert za notranje invariante, ne za preverjanje vhodnih podatkov, nadzor dostopa ali obravnavo napak, po katerih se lahko izvajanje nadaljuje. Nujne operacije, kot je ++count, naj bodo zunaj trditev. V C++23 makro sprejme en argument: če izraz vsebuje vejico, ki ni zaščitena z okroglimi oklepaji, obdaja ves izraz z dodatnim parom okroglih oklepajev.

static_assert je deklaracija jezika, ne makro. Med prevajanjem preveri konstantni izraz. Če statična trditev ne drži, je program nepravilno tvorjen. NDEBUG tega preverjanja ne more izklopiti.

Primeri

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

Rezultat

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.

Če so preverjanja omogočena, program brez dodatnega argumenta izpiše `Reached the next statement.`. Z argumentom `extra` zapiše diagnostično sporočilo na standardni tok za napake in se konča pred izpisom te vrstice. Z `NDEBUG` vrstico izpiše tudi z argumentom `extra`, ker ne ovrednoti `argc == 1`.

Povezane lekcije

  • C++ · Lekcija 49 · Srednja · Različica: 2

Viri