它为以下代码报告An invalid handle was specified.:

 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之类的东西)或引用计数来解决此问题。

09-19 23:33