Smart Pointers
Quick Notes
Section titled “Quick Notes”Smart pointer quản lý lifetime tự động bằng RAII.
unique_ptr sở hữu duy nhất, nhẹ và là lựa chọn mặc định.
shared_ptr chia sẻ ownership; weak_ptr quan sát để tránh cycle.
Syntax
Section titled “Syntax”auto value = std::make_unique<int>(42);auto shared = std::make_shared<std::string>("cpp");Ownership Table
Section titled “Ownership Table”| Smart Pointer | Ownership |
|---|---|
std::unique_ptr<T> | Một owner, move-only |
std::shared_ptr<T> | Nhiều owner, reference counting |
std::weak_ptr<T> | Không sở hữu, lock để dùng tạm |
Example
Section titled “Example”struct Node{ int value; std::weak_ptr<Node> parent; std::vector<std::shared_ptr<Node>> children;};
auto root = std::make_shared<Node>();auto child = std::make_shared<Node>();child->parent = root;root->children.push_back(child);Common Mistakes
Section titled “Common Mistakes”- Tạo hai
shared_ptrtừ cùng một raw pointer. - Dùng
shared_ptrmặc định cho mọi ownership, gây cycle hoặc overhead. - Quên kiểm tra kết quả
weak_ptr::lock().
Search Keywords
Section titled “Search Keywords”smart pointers con trỏ thông minh unique_ptr shared_ptr weak_ptr ownership raii make_unique make_shared