tinycodinglm / cpp /cpp26-features-003.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame
1.94 kB
opencode trace
System 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 c...

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.

User

Explain C++26 contracts and how to use them

Assistant

C++26 Contracts (P2900R14):

Basic Syntax:

cpp
// Preconditions
[[pre: x > 0]]
int safe_sqrt(int x) {
    return std::sqrt(x);
}

// Postconditions
[[ensures(r: r > 0)]]
int positive_result(int x) {
    return x * 2;
}

// Assertions
void process(int n) {
    [[assert: n > 0 && n < 100]];
    // ... process n ...
}

Contract Violation Handler:

cpp
#include <contracts>

// Custom handler
void my_handler(const std::contracts::contract_violation& violation) {
    std::cerr << "Contract violated: "
              << violation.what() << "\n";
    std::cerr << "At: " << violation.location() << "\n";
    std::abort();
}

// Set handler
std::contracts::set_violation_handler(my_handler);

Return Value Constraints:

cpp
// Function must return positive value
[[ensures(r: r > 0)]]
int get_positive(int x) {
    return std::abs(x);
}

Contract Levels:

  • [[pre: expr]] - checked (may throw)
  • [[pre(expecting_violation): expr]] - advisory
  • [[pre(announcing_violation): expr]] - logged only

Use Cases:

  • API boundary validation
  • Internal invariants
  • Debug assertions
  • Design-by-contract patterns