就我所知,涉及资源管理时,在堆上分配内存(使用 new
运算符)通常比在栈上(自动存储)分配要慢,因为栈是基于 LIFO 结构的,因此需要做最少的记录,下一个可用地址的指针很容易确定。
到目前为止,一切都好。现在看看以下代码:
/* ...includes... */
using std::cout;
using std::cin;
using std::endl;
int bar() { return 42; }
int main()
{
auto s1 = std::chrono::steady_clock::now();
std::packaged_task<int()> pt1(bar);
auto e1 = std::chrono::steady_clock::now();
auto s2 = std::chrono::steady_clock::now();
auto sh_ptr1 = std::make_shared<std::packaged_task<int()> >(bar);
auto e2 = std::chrono::steady_clock::now();
auto first = std::chrono::duration_cast<std::chrono::nanoseconds>(e1-s1);
auto second = std::chrono::duration_cast<std::chrono::nanoseconds>(e2-s2);
cout << "Regular: " << first.count() << endl
<< "Make shared: " << second.count() << endl;
pt1();
(*sh_ptr1)();
cout << "As you can see, both are working correctly: "
<< pt1.get_future().get() << " & "
<< sh_ptr1->get_future().get() << endl;
return 0;
}
结果似乎与上面解释的内容相矛盾:
常规:6131
使共享:843
正如您所看到的,两者都在正常工作: 42&amp; 42
程序以退出代码0结束
在第二次测量中,除了调用运算符 new
之外, std :: shared_ptr
( auto sh_ptr1
)的构造函数也必须完成。我似乎无法理解为什么这比常规分配更快。
这是什么原因呢?