Thuta Learning
C++
AdvancedProgrammingbeginner

RAII & Smart Pointers

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • RAII & Smart Pointers ရဲ့type, lifetime နဲ့runtime behavior ကိုရှင်းပြနိုင်ရန်
  • Warnings နဲ့sanitizers သုံးပြီးfailure cases စမ်းနိုင်ရန်
  • Modern, safe C++ code ရေးနိုင်ရန်

RAII & Smart Pointers ကိုsyntax ထက် object lifetime, ownership, borrowing, invalidation နဲ့exception safety contract အဖြစ်နားလည်ပါ။ Resource ကိုraw new/delete ဖြင့်မပိုင်ဆိုင်ဘဲRAII value types နဲ့smart pointers သုံးပြီးdangling access နဲ့double release ကိုdesign အဆင့်ကကာကွယ်ပါ။

ပိုပြီးနားလည်ထားရမယ့် အချက်

RAII & Smart Pointers ကိုsyntax ထက် object lifetime, ownership, borrowing, invalidation နဲ့exception safety contract အဖြစ်နားလည်ပါ။ Resource ကိုraw new/delete ဖြင့်မပိုင်ဆိုင်ဘဲRAII value types နဲ့smart pointers သုံးပြီးdangling access နဲ့double release ကိုdesign အဆင့်ကကာကွယ်ပါ။

လက်တွေ့မှာ ဘယ်လိုအသုံးချမလဲ

RAII & Smart Pointers example ကိုempty, boundary, invalid နဲ့failure cases ဖြင့်စမ်းပြီး `-std=c++23 -Wall -Wextra -Wpedantic` နဲ့build ပါ။ Lifetime-sensitive code ကိုAddressSanitizer/UndefinedBehaviorSanitizer ဖြင့်ထပ်စစ်ပါ။

ဒီသင်ခန်းစာပြီးရင်

cpp
#include <iostream>
#include <memory>

struct Resource {
    ~Resource() { std::cout << "released\n"; }
};

int main() {
    auto resource = std::make_unique<Resource>();
    std::cout << "owned\n";
}
You should see
owned
released

ကိုယ်တိုင်စမ်းကြည့်ရန်

RAII & Smart Pointers example ကိုempty, boundary, invalid နဲ့failure cases ဖြင့်စမ်းပြီး `-std=c++23 -Wall -Wextra -Wpedantic` နဲ့build ပါ။ Lifetime-sensitive code ကိုAddressSanitizer/UndefinedBehaviorSanitizer ဖြင့်ထပ်စစ်ပါ။

Memory/Safety သတိပေးချက်

Output တစ်ကြိမ်မှန်ရုံဖြင့် lifetime, bounds, ownership နဲ့undefined behavior အားလုံးမှန်ပြီဟုယူဆခြင်း။

C++ Core GuidelinesStandard C++ Foundation

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Output တစ်ကြိမ်မှန်ရုံဖြင့် lifetime, bounds, ownership နဲ့undefined behavior အားလုံးမှန်ပြီဟုယူဆခြင်း။
  • Raw pointer သို့iterator တစ်ခုကိုowner container/resource ပြောင်းပြီးနောက်လည်းvalid ဖြစ်နေမယ်ဟုယူဆခြင်း။

လက်တွေ့လေ့ကျင့်ခန်း

RAII & Smart Pointers example ကိုempty, boundary, invalid နဲ့failure cases ဖြင့်စမ်းပြီး `-std=c++23 -Wall -Wextra -Wpedantic` နဲ့build ပါ။ Lifetime-sensitive code ကိုAddressSanitizer/UndefinedBehaviorSanitizer ဖြင့်ထပ်စစ်ပါ။

You'll know it worked when: owned released

RAII & Smart Pointers | Thuta Learning