共享指针和独占指针

智能指针

  1. 不能将 shared_ptr 转换为 unique_ptr,这个很好理解。因为转换时我没办法只通过count去把其他的共享指针也给销毁掉。
  2. unique_ptr 可以转换为 shared_ptr(通过 std::move,转移指针的所有权)。

如果函数需要返回一个智能指针,建议返回独占指针。因为独占指针可以随时转换为共享指针。

使用示例
unique_ptr<cat> create_cat(const string& name)
{
  return make_unique<cat>(name);
}

int main()
{
  
  unique_ptr<cat> my_cat = create_cat("Tom");
  //转移所有权到 共享指针,此时my_cat已经失效
  shared_ptr<cat> another_cat = move(my_cat);
  another_cat->cat_info();

  //可以直接接受
  shared_ptr<cat> p3 = create_cat("aaa");
  if (p3)
  {
  	p3->cat_info();
  	cout << "p3 use_count: " << p3.use_count() << endl;
  }
}
posted @ 2025-12-24 21:55  Ytytyty  阅读(0)  评论(0)    收藏  举报