Why std :: tr1 :: shared_ptr <>. Is reset () so expensive?

Profiling some code that uses shared_ptrs heavily, I found that reset () was unexpectedly expensive.

For instance:

 struct Test { int i; Test() { this->i = 0; } Test(int i) { this->i = i; } } ; ... auto t = make_shared<Test>(1); ... t.reset(somePointerToATestObject); 

Tracking reset () on the last line (in VC ++ 2010), I found that it was creating a new reference counting object.

Is there a cheaper way that reuses an existing link count and doesn't bother a bunch?

+4
source share
1 answer

In general, you cannot reuse an existing reference counter because there may be other shared_ptr or weak_ptr .

If you can create somePointerToATestObject using make_shared() , then the implementation can use the same heap distribution for both ref and object references. This will save you from one of the heap allocations.

+4
source

Source: https://habr.com/ru/post/1312873/


All Articles