【发布时间】:2020-01-01 13:33:29
【问题描述】:
阅读关于在 C++ 中实现 Go 的延迟的问题后:
我对其中一个答案中给出的 go-defer like guard 子句的性能有疑问。 它使用了一个 shared_ptr 删除器,它忽略了传递的对象地址。
如果删除器忽略了使用未命名参数的地址,它是否仍会在堆栈上传递。
以下任何一种方式完成defer会有什么不同吗?
#include <memory>
#include <iostream>
#include <functional>
using namespace std;
using defer = shared_ptr<void>;
int main() {
defer defer0 (nullptr, [](...) { cout << "defer0\n"; }); // this is the version i've seen
// but will the performance be any different using any of these?
shared_ptr<int> defer1(nullptr, [](int* dummy) { cout << "defer1\n"; });
shared_ptr<int> defer2(nullptr, [](int*) { cout << "defer2\n"; });
shared_ptr<void> defer3(nullptr, [](void*) { cout << "defer3\n"; });
unique_ptr<int,void(*)(int*)> defer4(nullptr, [](int*) { cout << "defer4\n"; });
cout << "Hello\n";
}
【问题讨论】:
-
为什么不为此编写一个类而不是滥用智能指针?
-
它不适用于
unique_ptr,因为它的析构函数不会在 null (see here) 上调用删除器
标签: c++ deferred scopeguard