我已经阅读了问题weak_ptr的性能损失是什么?但我自己的测试显示不同的结果.
我正在为聪明的指针做代表.下面的简单代码显示了重现性能问题weak_ptr.谁能告诉我为什么?
#include <chrono>
#include <functional>
#include <iostream>
#include <memory>
#include <stdint.h>
#include <string>
#include <utility>
struct Foo
{
Foo() : counter(0) { incrStep = 1;}
void bar()
{
counter += incrStep;
}
virtual ~Foo()
{
std::cout << "End " << counter << std::endl;
}
private:
uint64_t counter;
uint64_t incrStep;
};
void pf(const std::string &md, const std::function<void()> &g)
{
const auto st = std::chrono::high_resolution_clock::now();
g();
const auto ft = std::chrono::high_resolution_clock::now();
const auto del = std::chrono::duration_cast<std::chrono::milliseconds>(ft - …Run Code Online (Sandbox Code Playgroud) 我已经读过创建或复制std :: shared_ptr涉及一些开销(参考计数器的原子增量等).
但是如何从它创建一个std :: weak_ptr:
Obj * obj = new Obj();
// fast
Obj * o = obj;
// slow
std::shared_ptr<Obj> a(o);
// slow
std::shared_ptr<Obj> b(a);
// slow ?
std::weak_ptr<Obj> c(b);
Run Code Online (Sandbox Code Playgroud)
我希望在一些更快的性能,但我知道共享指针仍然必须递增弱引用计数器..所以这仍然像将shared_ptr复制到另一个慢?