gpt4 book ai didi

c++ - cout 覆盖了我的一些指针

转载 作者:行者123 更新时间:2023-11-30 03:36:07 25 4
gpt4 key购买 nike

我有一个奇怪的问题,一个简单的 cout 弄乱了我之前定义的指针。这是代码:

union Value {
bool a;
long long val;
int next;
};

struct Clos { //not a "closure" in its actual sense.
vector<Value**> args;
function<void()> method;
};

Clos* prepare() {
Clos* closure = new Clos();

Value* a = nullptr; //these values do not exist yet, but I need these pointers to rename them at RT
Value* b = nullptr;
Value* out = new Value; //this exists
closure->args.push_back(&a); //save adresses to rename them later
closure->args.push_back(&b);
closure->method = [&a, &b, &out](){out->val = a->val + b->val;}; //just some operation on arguments
return closure;
}

在这里,我创建了一个带有绑定(bind)函数(一种“方法”)的对象“闭包”,它使用尚未定义的指针作为参数,稍后将在运行时绑定(bind)。

后来:

 int main(void) {
Clos* clos = prepare();
Value a; //now we get input values at RT
a.val = 7;
Value b;
b.val = 8;
*clos->args[0] = &a; //we bind them to previously "dangling" pointers
*clos->args[1] = &b;
cout << "WOLOLOLOLO"; //<<<<---- COMMENT OUT THIS LINE AND BOOM!
clos->method(); //this works, as long cout is not called
}

我最初定义 a 和 b(作为空指针?)的方式有问题吗?它们会被释放还是什么?我试过使它们“静态”,但它也不起作用。总的来说有些问题:(

最佳答案

主要问题在这里:

closure->method = [&a, &b, &out](){out->val = a->val + b->val;};

这个 lambda 正在创建一个引用局部变量的闭包。一旦变量超出范围,这个闭包就不再可调用。我想你想要更像这样的东西:

#include <vector>
#include <iostream>
#include <functional>

using std::vector;
using std::function;
using std::cout;


union Value {
bool a;
long long val;
int next;
};

struct Clos { //not a "closure" in its actual sense.
vector<Value*> args;
function<void()> method;

~Clos()
{
for (auto &arg : args) {
delete arg;
}
}
};

Clos* prepare() {
Clos* closure = new Clos();

Value* a = new Value;
Value* b = new Value;
Value* out = new Value; //this exists
closure->args.push_back(a);
closure->args.push_back(b);
closure->args.push_back(out);

// Make copies of the pointers, not references.
closure->method = [a, b, out](){out->val = a->val + b->val;};

return closure;
}

int main(void) {
Clos* clos = prepare();
Value a; a.val = 7;
Value b; b.val = 8;
*clos->args[0] = a;
*clos->args[1] = b;
clos->method();
cout << clos->args[2]->val << "\n";

delete clos;
}

关于c++ - cout 覆盖了我的一些指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40831272/

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