开发者

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

开发者 https://www.devze.com 2023-01-03 18:02 出处:网络
Profiling some code that heavily uses shared_ptrs, I discovered that reset() was surprisingly expensive.

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_ptrs or weak_ptrs 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消