Pointers, RAII & Smart Pointers
Raw pointers, new/delete, RAII, unique_ptr, shared_ptr and weak_ptr.
Key PointsRAII ties resource lifetime to scope; modern C++ uses smart pointers, not new/delete.
C++
#include <memory>
#include <iostream>
void use() {
auto up = std::make_unique<int>(10); // exclusive ownership
auto sp = std::make_shared<int>(20); // refcounted ownership
std::weak_ptr<int> wp = sp; // break cycles
std::cout << *up << ' ' << *sp << '\n';
} // freed automaticallyshared_ptr cycles leak; store weak_ptr for back-references (e.g. parent links).
C++
#include <memory>
#include <iostream>
void use() {
auto up = std::make_unique<int>(10); // exclusive ownership
auto sp = std::make_shared<int>(20); // refcounted ownership
std::weak_ptr<int> wp = sp; // break cycles
std::cout << *up << ' ' << *sp << '\n';
} // freed automaticallyshared_ptr 循环引用会泄漏;反向引用(如父节点)用 weak_ptr。