gpt4 book ai didi

C++析构函数过早调用

转载 作者:行者123 更新时间:2023-11-30 02:42:10 25 4
gpt4 key购买 nike

我已将代码简化为仍然存在问题的最小样本。此代码应打印“42”,但打印的是一个不同的数字。我还在析构函数中打印“Secret”对象的地址,以及何时访问它,以表明它被过早销毁。我在这里做错了什么,还是编译器有问题?

代码:

#include <iostream>    

using namespace std;

struct Secret{
int value;
Secret(int value):value(value){}
~Secret(){
cout<<"destructor:"<<(void*)this<<endl;
value=0;
}
};

template<class Func>
class Copier{
public:
Func func;
Copier(Func func):func(func){}
void run(){
func();
}
auto copy(){
auto output = [this](){
func();
};
Copier<decltype(output)> out(output);
return out;
}

};
auto makeSecretPrinter(){
Secret secret(42);
auto secretPrinter = [secret](){
cout<<"reading object at address:"<<(void*)&secret<<endl;
cout<<"the secret is:"<<secret.value<<endl;
};
return Copier<decltype(secretPrinter)>(secretPrinter).copy();
}

int main(){
makeSecretPrinter().run();
return 0;
}

clang(版本 3.5-1ubuntu1)输出:

destructor:0x7fff9e3f9940
destructor:0x7fff9e3f9938
destructor:0x7fff9e3f9948
destructor:0x7fff9e3f9950
reading object at address:0x7fff9e3f9940
the secret is:0

GCC (Ubuntu 4.9.2-0ubuntu1~14.04) 4.9.2 输出:

destructor:0x7fff374facc0
destructor:0x7fff374facb0
destructor:0x7fff374faca0
destructor:0x7fff374fac90
reading object at address:0x7fff374facc0
the secret is:-1711045632

最佳答案

捕获 this 使用指针语义进行捕获。改变这个:

auto output = [this](){
func();
};

这解决了问题:

auto output = [self=*this](){
self.func();
};

关于C++析构函数过早调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27350425/

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