通过简单的包装指针C++智能指针性能和差异

C++ smart pointer performance and difference with a simple wrapped pointer

本文关键字:指针 性能 智能 C++ 简单 包装      更新时间:2023-10-16

我遇到了有人C++在智能指针上做的这个测试,我想知道几件事。首先,我听说make_shared和make_unique比共享或唯一指针的正常构造更快。但是我的结果和创建测试的人的结果表明,make_unique和make_shared稍微慢一些(可能没什么大不了的)。但我也想知道,在调试模式下,对我来说,unique_pointer比普通指针慢大约 3 倍,实际上也比我自己简单地将指针包装在类中慢得多。在发布模式下,原始指针、我的包装类和unique_ptrs大致相同。我想知道,如果我使用自己的智能指针,unique_pointer会有什么特别的事情吗?它似乎相当沉重,至少在调试模式下它似乎做了很多事情。测试如下:

#include <chrono>
#include <iostream>
#include <memory>
static const long long numInt = 100000000;
template <typename T>
struct SmartPointer
{
SmartPointer(T* pointee) : ptr(pointee) {}
T* ptr;
~SmartPointer() { delete ptr; }
};
int main() {
auto start = std::chrono::system_clock::now();
for (long long i = 0; i < numInt; ++i) {
//int* tmp(new int(i));
//delete tmp;
//SmartPointer<int> tmp(new int(i));
//std::shared_ptr<int> tmp(new int(i));
//std::shared_ptr<int> tmp(std::make_shared<int>(i));
//std::unique_ptr<int> tmp(new int(i));
//std::unique_ptr<int> tmp(std::make_unique<int>(i));
}
std::chrono::duration<double> dur = std::chrono::system_clock::now() - start;
std::cout << "time native: " << dur.count() << " seconds" << std::endl;
system("pause");
}

我找到它的链接位于 http://www.modernescpp.com/index.php/memory-and-performance-overhead-of-smart-pointer

据我所知,实际问题是:

我想知道,如果我使用自己的智能指针,unique_pointer会有什么特别的事情吗?它似乎相当沉重,至少在调试模式下它似乎做了很多事情。

unique_ptr可能有更琐碎的函数调用或类似的东西,这些调用不会完全内联,从而导致调试模式下的性能变差。但是,正如您自己所说,在启用优化的情况下,关键时的性能是相同的。

尽管unique_ptr是最简单的拥有智能指针来编写,但它仍然做了很多你的琐碎包装器没有做的事情:

它允许自定义删除程序
  • ,同时通过空基类优化确保无状态自定义删除程序不会使用额外的空间
  • 它可以正确处理移动和复制
  • 它正确地处理所有类型的转换;例如,unique_ptr<Derived>将隐式转换为unique_ptr<Base>
  • 这是正确的

虽然大多数体面的C++程序员都可以实现一个体面的unique_ptr,但我不认为大多数人能实现一个完全正确的。这些边缘情况会伤害你。

只需使用unique_ptr,在关闭优化的情况下滚动自己的以获得更好的性能不是一个很好的理由。