共享 PTR - C++:std::shared_ptr<T> 和 std::shared_ptr<T const> 有什么区别?

shared ptr - C++: What is the difference between std::shared_ptr<T> and std::shared_ptr<T const>?

本文关键字:lt gt ptr shared std 什么 区别 const PTR 共享 C++      更新时间:2023-10-16

std::shared_ptr<T>std::shared_ptr<T const>之间有什么区别?

你什么时候会使用其中一种与另一种?

  • shared_ptr<int>是一个shared_ptr到一个非常数int。您可以修改int和shared_ptr

  • shared_ptr<const int>shared_ptrconst int。不能修改shared_ptr指向的const int,因为它是const。但是您可以修改shared_ptr本身(分配给它,调用其他非常量方法,等等)

  • const shared_ptr<int>const shared_ptr到非常量int。你不能修改shared_ptr(通过调用reset或任何非常量方法),但你可以修改它指向的int

  • const shared_ptr<const int>const shared_ptrconst int。你不能修改jack。

shared_ptr<T>

在引擎盖下存储一个T*,而

shared_ptr<T const>

在引擎盖下存储一个T常量*。因此,它与指向某些数据的指针和指向某些常量数据的指针之间的差异相同。

当你只想让shared_ptr表现得像一个普通指针(带有引用计数)时,你会使用它;当你想存储一个引用计数的指针到一些常量数据(你从来没有想要修改的数据)时,也会使用shared_ptr。)回想一下,指向常量数据的指针(不能修改所指向的数据,但可以修改指针)和常量指针(可以修改所指向数据,但不能修改指针本身)之间有区别。