auto itor = DrawList.begin();
while (itor != DrawList.end())
{
(*itor)->Paint();
printf("use_count = %d", (*itor).use_count());
itor++;
}
for (shared_ptr<GameObject>& ptr : DrawList)
{
(*ptr).Paint();
printf("use_count = %d", ptr.use_count());
}
for (shared_ptr<GameObject> ptr : DrawList)
{
(*ptr).Paint();
printf("use_count = %d", ptr.use_count());
}
前两个遍历都没问题,智能指针引用不会增加。 第三个很坑,每一次循环会创建临时变量,引用计数+1,结束的时候-1,这样每次循环显示COPY一次 然后引用计数 增减一次,性能肯定不好
以前都没注意到这个问题。 遍历的时候 最好用前两种方法。