簡體   English   中英

C ++:std :: shared_ptr和有什么不一樣 <T> 和std :: shared_ptr <T const> ?

[英]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_ptrconst int 您不能修改shared_ptr指向的const int ,因為它是const 但是您可以修改shared_ptr本身(分配給它,調用其他非const方法,等等)

  • const shared_ptr<int>是非const intconst shared_ptr 您不能修改shared_ptr (通過調用reset或任何非const方法),但是可以修改它指向的int

  • const shared_ptr<const int>是一個const shared_ptrconst 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM