Modern C++ और C Alternatives

RAII और Deterministic Cleanup

RAII exception सहित हर scope exit पर automatic cleanup करता है।

RAII और Deterministic Cleanup क्या है?

RAII exception सहित हर scope exit पर automatic cleanup करता है।

Resource lifetime को object lifetime से जोड़ें।

महत्वपूर्ण बातें

  • पहले C mechanism समझें।
  • Ownership के लिए RAII और value semantics उपयोग करें।
  • Macros और casts से अधिक type-safe abstractions चुनें।

C और C++ code examples

C
कोड चलाएँ →
main.c
#include <stdio.h>

int main(void) {
    int result = 1;
    FILE *file = fopen("scores.txt", "w");
    if (!file) goto cleanup;
    if (fputs("Ada 95\n", file) < 0) goto cleanup;
    result = 0;

cleanup:
    if (file) fclose(file);
    puts(result ? "failed" : "saved");
    return result;
}
अपेक्षित output
saved
C++
कोड चलाएँ →
main.cpp
#include <fstream>
#include <iostream>

int main() {
    std::ofstream file("scores.txt");
    if (!file) return 1;
    file << "Ada 95\n";
    std::cout << "saved\n";
}
अपेक्षित output
saved

C और C++ की तुलना

C cleanup label से हर path पर fclose करता है; C++ fstream destructor में close होकर ownership local रखता है।

C

C prefixes, callbacks, macros और context structs उपयोग करता है।

C++

Language scoped और type-safe abstractions देता है।

अभ्यास

दोनों versions चलाकर बदलें और language guarantees की तुलना करें।

  • पहले C mechanism लिखें।
  • Manual cleanup को RAII से बदलें।
  • Allocation और virtual dispatch जाँचें।