调用vector的clear()会触发其中每个std::shared_ptr执行reset()吗?
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 callreset()on eachstd::shared_ptrinside?
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():
- The vector iterates over every element (each
std::shared_ptr<AbstractPathContainer>) and destroys them one by one. - When a
std::shared_ptris destroyed, its destructor does the exact same work as callingreset():- It decrements the reference count of the managed
AbstractPathContainerobject. - 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).
- It decrements the reference count of the managed
Extra Notes
- You don't need to manually loop through the vector and call
reset()on each element beforeclear()—that's totally redundant. The vector'sclear()method already handles cleaning up theshared_ptrinstances properly. - Keep in mind: if other
std::shared_ptrinstances (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
相关产品推荐
相关产品推荐

