Profiling some code that heavily uses shared_ptrs, I discovered that reset() was surprisingly expensive.
For example:
struct Test {
int i;
Test() {
this->i = 0;
}
开发者_运维问答 Test(int i) {
this->i = i;
}
} ;
...
auto t = make_shared<Test>(1);
...
t.reset(somePointerToATestObject);
Tracing the reset() in the last line (under VC++ 2010), I discovered that it creates a new reference-counting object.
Is there a cheaper way, that reuses the existing ref-count and does not bother the heap?
In the general case, you can't reuse the existing ref count because there may be other shared_ptr
s or weak_ptr
s using it.
If you can create somePointerToATestObject
using make_shared()
, then the implementation may use a single heap allocation for both the ref counts and the object. That will save you one of the heap allocations.
精彩评论