gpt4 book ai didi

c++ - 是在 C 或 C++ 析构函数中模拟 GO 语言延迟的实用方法吗?

转载 作者:IT王子 更新时间:2023-10-29 02:28:58 28 4
gpt4 key购买 nike

简而言之:它是一道C题中的智能指针。原因:嵌入式编程,需要确保如果使用了复杂的算法,则开发人员只需付出很少的努力即可进行适当的重新分配。

我最喜欢的 C++ 功能是能够对分配在堆栈上且超出范围的对象执行适当的重新分配。 GO 语言 defer 提供相同的功能,并且在精神上更接近 C。

GO defer 将是在 C 中做事的理想方式。是否有实用的方法来添加此类功能?

这样做的目的是简化跟踪对象何时何地超出范围。这是一个简单的例子:

struct MyDataType *data = malloc(sizeof(struct MyDataType));
defer(data, deallocator);
if (condition) {
// dallocator(data) is called automatically
return;
}
// do something
if (irrelevant) {
struct DT *localScope = malloc(...);
defer(localScope, deallocator);
// deallocator(localScope) is called when we exit this scope
}
struct OtherType *data2 = malloc(...);
defer(data2, deallocator);
if (someOtherCondition) {
// dallocator(data) and deallocator(data2) are called in the order added
return;
}

在其他语言中,我可以在代码块内创建一个匿名函数,将其分配给变量并在每次返回前手动执行。这至少是部分解决方案。在 GO 语言中,延迟函数可以被链接。在 C 中使用匿名函数手动链接容易出错且不切实际。

谢谢

最佳答案

在 C++ 中,我见过遵循 RAII 模式的“基于堆栈的类”。您可以制作一个通用的 Defer 类(或结构),它可以接受任意函数或 lambda。

例如:

#include <cstddef>
#include <functional>
#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::function;
using std::string;

struct Defer {
function<void()> action;
Defer(function<void()> doLater) : action{doLater} {}
~Defer() {
action();
}
};

void Subroutine(int i) {
Defer defer1([]() { cout << "Phase 1 done." << endl; });
if (i == 1) return;
char const* p = new char[100];
Defer defer2([p]() { delete[] p; cout << "Phase 2 done, and p deallocated." << endl; });
if (i == 2) return;
string s = "something";
Defer defer3([&s]() { s = ""; cout << "Phase 3 done, and s set to empty string." << endl; });
}

int main() {
cout << "Call Subroutine(1)." << endl;
Subroutine(1);
cout << "Call Subroutine(2)." << endl;
Subroutine(2);
cout << "Call Subroutine(3)." << endl;
Subroutine(3);
return EXIT_SUCCESS;
}

关于c++ - 是在 C 或 C++ 析构函数中模拟 GO 语言延迟的实用方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48117908/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com