Skip to content

Smart Pointers

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.

auto value = std::make_unique<int>(42);
auto shared = std::make_shared<std::string>("cpp");
Smart PointerOwnership
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
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);
  • Tạo hai shared_ptr từ cùng một raw pointer.
  • Dùng shared_ptr mặc định cho mọi ownership, gây cycle hoặc overhead.
  • Quên kiểm tra kết quả weak_ptr::lock().

smart pointers con trỏ thông minh unique_ptr shared_ptr weak_ptr ownership raii make_unique make_shared