Sta*_*ser 6 c++ smart-pointers reference-counting shared-ptr
我有一个问题,请通过以下简单的C++程序,
int main( )
{
shared_ptr<int> sptr1( new int );
shared_ptr<int> sptr2 = sptr1;
shared_ptr<int> sptr3;
shared_ptr<int> sptr4;
sptr3 = sptr2;
cout<<sptr1.use_count()<<endl;
cout<<sptr2.use_count()<<endl;
cout<<sptr3.use_count()<<endl;
sptr4 = sptr2;
cout<<sptr1.use_count()<<endl;
cout<<sptr2.use_count()<<endl;
cout<<sptr3.use_count()<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
3
3
3
4
4
4
Run Code Online (Sandbox Code Playgroud)
如何sptr1和sptr3对象知道引用计数在打印4时递增.
据我所知,引用计数是每个shared_ptr对象中的变量.
Vit*_*meo 14
据我所知,引用计数是每个shared_ptr对象中的变量.
不,引用计数存储在堆上的"控制块"中.每个shared_ptr实例指向相同的"控制块"并使其保持活动状态(直到所有实例和weak_ptr与它们共享所有权的所有实例都已死).
| 归档时间: |
|
| 查看次数: |
676 次 |
| 最近记录: |