CKTIS / C++
assert a NDEBUG: vypínatelné kontroly za běhu
`assert` kontroluje interní předpoklad programu za běhu. Definice `NDEBUG` může kontrolu vypnout, aniž se vyhodnotí podmínka. Na `static_assert` nemá vliv.
Verze: ISO C++23; implementation support may vary
Syntaxe
#include <cassert>
assert(condition);V C++23 je assert(condition) z <cassert> makro s parametrem, nikoli funkce jménem std::assert. Pokud je kontrola zapnutá a běh programu k ní dospěje, vyhodnotí se podmínka skalárního typu. Je-li výsledek různý od nuly, program pokračuje. Jinak makro vypíše diagnostické hlášení do standardního chybového proudu a zavolá std::abort(), čímž program nestandardně ukončí. Formát hlášení určuje implementace.
Pokud je NDEBUG definováno při vložení <cassert>, assert(condition) se rozvine na ((void)0) a podmínka se nevyhodnotí. Záleží jen na existenci definice: aserce vypne i #define NDEBUG 0. Při každém vložení hlavičky se použije aktuální stav NDEBUG. Pozdější změna bez opětovného vložení hlavičky nezmění existující definici assert. Název konfigurace, například Release, sám o sobě nerozhoduje.
Používej assert pro interní invarianty, ne pro validaci vstupu, kontrolu přístupu ani ošetření chyb, ze kterých se program může zotavit. Nezbytné operace jako ++count prováděj mimo aserci. V C++23 makro přijímá jeden argument: pokud výraz obsahuje čárku nechráněnou kulatými závorkami, uzavři celý výraz do další dvojice kulatých závorek.
static_assert je deklarace jazyka, nikoli makro. Kontroluje konstantní výraz při překladu. Selže-li statická aserce, program není správně utvořený. NDEBUG ji nemůže vypnout.
Příklady
#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);
}Výsledek
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.
Se zapnutými asercemi program bez dalšího argumentu vypíše `Reached the next statement.`. S argumentem `extra` vypíše diagnostické hlášení do standardního chybového proudu a skončí před výpisem tohoto řádku. S `NDEBUG` vypíše řádek i s argumentem `extra`, protože `argc == 1` nevyhodnocuje.
Související lekce
- C++ · Lekce 49 · Středně pokročilá · Verze: 2