{"type": "session", "harness": "opencode", "id": "cpp26-features-003", "name": "C++26 contracts and assertions"} {"type": "message", "message": {"role": "system", "content": "You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies."}} {"type": "message", "message": {"role": "user", "content": "Explain C++26 contracts and how to use them"}} {"type": "message", "message": {"role": "assistant", "content": "**C++26 Contracts (P2900R14):**\n\n**Basic Syntax:**\n```cpp\n// Preconditions\n[[pre: x > 0]]\nint safe_sqrt(int x) {\n return std::sqrt(x);\n}\n\n// Postconditions\n[[ensures(r: r > 0)]]\nint positive_result(int x) {\n return x * 2;\n}\n\n// Assertions\nvoid process(int n) {\n [[assert: n > 0 && n < 100]];\n // ... process n ...\n}\n```\n\n**Contract Violation Handler:**\n```cpp\n#include \n\n// Custom handler\nvoid my_handler(const std::contracts::contract_violation& violation) {\n std::cerr << \"Contract violated: \"\n << violation.what() << \"\\n\";\n std::cerr << \"At: \" << violation.location() << \"\\n\";\n std::abort();\n}\n\n// Set handler\nstd::contracts::set_violation_handler(my_handler);\n```\n\n**Return Value Constraints:**\n```cpp\n// Function must return positive value\n[[ensures(r: r > 0)]]\nint get_positive(int x) {\n return std::abs(x);\n}\n```\n\n**Contract Levels:**\n- `[[pre: expr]]` - checked (may throw)\n- `[[pre(expecting_violation): expr]]` - advisory\n- `[[pre(announcing_violation): expr]]` - logged only\n\n**Use Cases:**\n- API boundary validation\n- Internal invariants\n- Debug assertions\n- Design-by-contract patterns"}}