![](/img/trans.png)
[英]Is there an implicit conversion from std::shared_ptr<T> to std::shared_ptr<const T>?
[英]C++: What is the difference between std::shared_ptr<T> and std::shared_ptr<T const>?
std::shared_ptr<T>
和std::shared_ptr<T const>
什么區別?
以及何時使用一個與另一個?
shared_ptr<int>
是一個shared_ptr
一個非const int
。 您可以修改int和shared_ptr
shared_ptr<const int>
是一個shared_ptr
到const int
。 您不能修改shared_ptr
指向的const int
,因為它是const
。 但是您可以修改shared_ptr
本身(分配給它,調用其他非const方法,等等)
const shared_ptr<int>
是非const int
的const shared_ptr
。 您不能修改shared_ptr
(通過調用reset
或任何非const方法),但是可以修改它指向的int
const shared_ptr<const int>
是一個const shared_ptr
到const int
。 您無法修改插孔。
shared_ptr<T>
在引擎蓋下存儲T *,而
shared_ptr<T const>
在引擎蓋下存儲T const *。 因此,這與指向某些數據的指針和指向某些常量數據的指針之間的區別相同。
當您只希望shared_ptr表現得像常規指針(帶有引用計數)時,就可以使用shared_ptr,並且當您要存儲指向某些常量數據的引用計數的指針(您永遠不想修改的數據)時,可以使用shared_ptr 。)回想一下,指向常量數據的指針(不能修改指向的數據,但是可以修改指針)與常量指針(可以修改指向的數據,但是指針本身沒有區別)。 )最后,有一個指向常量數據的常量指針,您既不能修改指向的數據,也不能修改指針本身。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.