c – 空的别名shared_ptr是一个不起作用的删除shared_ptr的好选择?

前端之家收集整理的这篇文章主要介绍了c – 空的别名shared_ptr是一个不起作用的删除shared_ptr的好选择?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有时候,我需要具有无操作删除器的shared_ptr实例,因为API期望一个shared_ptr实例,它希望在有限的时间内存储,但是我被给予一个原始指针,我不允许拥有一个比我正在跑

对于这种情况,我一直在使用一个无操作的删除程序,例如[](const void *){},但是今天我发现还有另一个选择,使用(或滥用)

  1. void f(ExpectedClass *ec) {
  2. std::shared_ptr<ExpectedClass> p(std::shared_ptr<void>(),ec);
  3. assert(p.use_count() == 0 && p.get() != nullptr);
  4. apiCall(p);
  5. }

我的问题是,做更好的方法是什么,为什么?性能预期是否一样?使用无操作的删除器,我希望为存储删除器和引用计数支付一些成本,这在使用具有空的shared_ptr的别名构造函数时似乎不是这样.

解决方法

关于表现,以下基准显示不规律的数字:
  1. #include <chrono>
  2. #include <iostream>
  3. #include <limits>
  4. #include <memory>
  5.  
  6. template <typename... Args>
  7. auto test(Args&&... args) {
  8. using clock = std::chrono::high_resolution_clock;
  9. auto best = clock::duration::max();
  10.  
  11. for (int outer = 1; outer < 10000; ++outer) {
  12. auto now = clock::now();
  13.  
  14. for (int inner = 1; inner < 20000; ++inner)
  15. std::shared_ptr<int> sh(std::forward<Args>(args)...);
  16.  
  17. auto time = clock::now()-now;
  18. if (time < best) {
  19. best = time;
  20. outer = 1;
  21. }
  22. }
  23.  
  24. return best.count();
  25. }
  26.  
  27. int main()
  28. {
  29. int j;
  30.  
  31. std::cout << "With aliasing ctor: " << test(std::shared_ptr<void>(),&j) << '\n'
  32. << "With empty deleter: " << test(&j,[] (auto) {});
  33. }

在我的机器上输出clang -march = native -O2:

  1. With aliasing ctor: 11812
  2. With empty deleter: 651502

具有相同选项的GCC具有更大的比例,5921:465794.而与-stdlib = libc的Clang产生了惊人的12:613175.

猜你在找的C&C++相关文章