有时候,我需要具有无操作删除器的shared_ptr实例,因为API期望一个shared_ptr实例,它希望在有限的时间内存储,但是我被给予一个原始指针,我不允许拥有一个比我正在跑
对于这种情况,我一直在使用一个无操作的删除程序,例如[](const void *){},但是今天我发现还有另一个选择,使用(或滥用)
- void f(ExpectedClass *ec) {
- std::shared_ptr<ExpectedClass> p(std::shared_ptr<void>(),ec);
- assert(p.use_count() == 0 && p.get() != nullptr);
- apiCall(p);
- }
我的问题是,做更好的方法是什么,为什么?性能预期是否一样?使用无操作的删除器,我希望为存储删除器和引用计数支付一些成本,这在使用具有空的shared_ptr的别名构造函数时似乎不是这样.
解决方法
关于表现,以下基准显示不规律的数字:
- #include <chrono>
- #include <iostream>
- #include <limits>
- #include <memory>
- template <typename... Args>
- auto test(Args&&... args) {
- using clock = std::chrono::high_resolution_clock;
- auto best = clock::duration::max();
- for (int outer = 1; outer < 10000; ++outer) {
- auto now = clock::now();
- for (int inner = 1; inner < 20000; ++inner)
- std::shared_ptr<int> sh(std::forward<Args>(args)...);
- auto time = clock::now()-now;
- if (time < best) {
- best = time;
- outer = 1;
- }
- }
- return best.count();
- }
- int main()
- {
- int j;
- std::cout << "With aliasing ctor: " << test(std::shared_ptr<void>(),&j) << '\n'
- << "With empty deleter: " << test(&j,[] (auto) {});
- }
在我的机器上输出clang -march = native -O2:
- With aliasing ctor: 11812
- With empty deleter: 651502
具有相同选项的GCC具有更大的比例,5921:465794.而与-stdlib = libc的Clang产生了惊人的12:613175.