You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用vector的clear()会触发其中每个std::shared_ptr执行reset()吗?

Does calling clear() on std::vector<std::shared_ptr<T>> call reset() on each shared_ptr?

I've recently replaced raw pointers in my code with std::shared_ptr, and stored them in a container like this:

std::vector<std::shared_ptr<AbstractPathContainer>> mGeneratedPaths;

I'm wondering: when I call clear() on this vector, will it call reset() on each std::shared_ptr inside?

Short Answer

Yes, the end result is exactly the same as calling reset() on each std::shared_ptr in the vector—though it happens indirectly through the shared_ptr destructor.

Detailed Breakdown

Here's what actually happens when you call mGeneratedPaths.clear():

  1. The vector iterates over every element (each std::shared_ptr<AbstractPathContainer>) and destroys them one by one.
  2. When a std::shared_ptr is destroyed, its destructor does the exact same work as calling reset():
    • It decrements the reference count of the managed AbstractPathContainer object.
    • If the reference count drops to 0 after this decrement, the managed object is deleted (or your custom deleter is triggered, if you provided one).

Extra Notes

  • You don't need to manually loop through the vector and call reset() on each element before clear()—that's totally redundant. The vector's clear() method already handles cleaning up the shared_ptr instances properly.
  • Keep in mind: if other std::shared_ptr instances (outside this vector) are pointing to the same objects, those objects won't be deleted until all references are gone. The underlying object only gets cleaned up when the reference count hits 0.

内容的提问来源于stack exchange,提问作者huy nguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:20:32