gpt4 book ai didi

c++ - 如何在 c/c++ 中修复此 "First-chance exception"?

转载 作者:搜寻专家 更新时间:2023-10-30 23:49:45 25 4
gpt4 key购买 nike

它报告指定了一个无效的句柄。下面的代码:

 if(hPipe)
CloseHandle(hPipe);

我能做什么?

最佳答案

我怀疑你有这样的事情:

class SmartPipe
{
HANDLE hPipe;
public:
//Functions which do something to hPipe
~SmartPipe()
{
if (hPipe)
CloseHandle(hPipe);
}
};

问题是当 SmartPipe 创建时,hPipe 被初始化为随机垃圾。你必须自己初始化它。将 hPipe 添加到类中的初始化列表中:

class SmartPipe
{
HANDLE hPipe;
public:
SmartPipe() : hPipe(0)
{
}
//Functions which do something to hPipe
~SmartPipe()
{
if (hPipe)
CloseHandle(hPipe);
}
};

如果这不是您的情况,至少检查 hPipe 是否在某处初始化,即使它被设置为 0 的值也是如此。

编辑:这是一个双重免费场景:

class SmartPipe
{
//As above
};

void SomeFunc(SmartPipe input) //Note pass by value
{ //At this point, the pipe object was copied
//2 SmartPipes are alive with the same handle value here.
//Do something with `input`
}

int main()
{
SmartPipe input;
//setup input somehow
SomeFunc(input);
//Note that at this point the pipe passed by value has already been
//destroyed, and the handle held by `input` has already been closed.
} //`input` destroyed here, resulting in a double free.

通过使 SmartPipe 不可复制,或为其编写复制句柄的复制构造函数和复制赋值运算符(使用类似 DuplicateHandle 的东西)或引用计数来解决这个问题。

关于c++ - 如何在 c/c++ 中修复此 "First-chance exception"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3689587/

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