返回资讯中心
外部精选
软件工程
#开发者实时流

Exploration of a more library-oriented approach to contracts

constexpr const char* comment() const noexcept;

Hacker News 最新bmacho2026/10/26 · 11 天前5 分钟阅读

以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。

struct assertion_context { constexpr const char* comment() const noexcept; constexpr std::source_location location() const noexcept; constexpr evaluation_semantic semantic() const noexcept; constexpr assertion_kind kind() const noexcept; constexpr bool check();

private: void* __args; // exposition-only bool (__check)(void); // exposition-only };

For invoking the violation handler, there is a function

void invoke_violation_handler(assertion_kind kind, evaluation_semantic semantic, detection_mode mode, const char* comment, std::source_location loc);

Implementation experience

This approach has been implemented in a fork of GCC, at https://github.com/villevoutilainen/gcc/tree/p4324.

The compiler is available on godbolt, as "X86-64 gcc (P4324 contracts)".

A pure-library version of quick_enforce; calls abort() on enforce, calls the violation handler on observe, ignores on ignore: Library quick_enforce on godbolt

A pure-library version of noexcept_enforce/noexcept_observe: Library noexcept_enforce/noexcept_observe on godbolt

Same example in the case where the handler throws: Library noexcept_enforce/noexcept_observe on godbolt, with a handler throw

An example of a contract that lets predicate exceptions through: A throwing predicate, exception passed through, on godbolt

Same example, but we catch the exception and call the violation handler: A throwing predicate, exception caught, on godbolt

An example of zero overhead (which can also be achieved with C++26 quick_enforce, but this shows it's attainable here too): Zero-overhead example

A contract that is always checked and always enforced: An always-on/enforced contract on godbolt

A contract that is ignored at run-time based on an environment variable: A run-time-ignored contract on godbolt

A contract that carries a custom diagnostic message: A contract with a custom message on godbolt

The facility integrated to the standard library, implementing the hardened standard library: Library hardening with P4324 on godbolt

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →