CKTIS / C++
assert e NDEBUG: controlli disattivabili a runtime
`assert` verifica un’ipotesi interna a runtime. Definire `NDEBUG` può disattivare il controllo senza valutare la condizione, ma non influisce su `static_assert`.
Versione: ISO C++23; implementation support may vary
Sintassi
#include <cassert>
assert(condition);In C++23, assert(condition) di <cassert> è una macro di tipo funzione, non una funzione chiamata std::assert. Se è attiva e l’esecuzione la raggiunge, valuta la condizione di tipo scalare. Se il risultato è diverso da zero, l’esecuzione prosegue. Altrimenti scrive un messaggio diagnostico sullo standard error e chiama std::abort(), terminando il programma in modo anomalo. Il formato del messaggio dipende dall’implementazione.
Se NDEBUG è definita quando si include <cassert>, assert(condition) si espande in ((void)0) e la condizione non viene valutata. Conta solo che la macro sia definita: anche #define NDEBUG 0 disattiva le asserzioni. Ogni inclusione dell’header usa lo stato corrente di NDEBUG; cambiarlo in seguito senza includere di nuovo l’header non modifica la definizione esistente di assert. Un nome di configurazione come Release non determina da solo questo comportamento.
Usa assert per le invarianti interne, non per convalidare gli input, controllare gli accessi o gestire errori recuperabili. Tieni le operazioni indispensabili, come ++count, fuori dalle asserzioni. In C++23 la macro accetta un solo argomento: se l’espressione contiene una virgola non protetta da parentesi tonde, racchiudi l’intera espressione in un’ulteriore coppia di parentesi tonde.
static_assert è una dichiarazione del linguaggio, non una macro. Controlla un’espressione costante in fase di compilazione. Se l’asserzione fallisce, il programma è mal formato. NDEBUG non può disattivarla.
Esempi
#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);
}Risultato
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.
Con le asserzioni attive, senza argomenti aggiuntivi il programma stampa `Reached the next statement.`. Con `extra` scrive un messaggio diagnostico sullo standard error e termina in modo anomalo prima di stampare la riga. Con `NDEBUG` la riga viene stampata anche con `extra`, perché `argc == 1` non viene valutata.
Lezioni correlate
- C++ · Lezione 49 · Intermedio · Versione: 2