Bin*_*ier 1 c++ windows winapi
伙计们,我正在试图追踪现场出现的间歇性错误.我觉得在一些GDI代码中我会拼凑起来让计算机打印机工作.
我对如何删除这个CDC感到困惑,我的代码看起来还不错,但这是正确的.
// Create a device context for printing
CDC* dc = new CDC();
if(! dc->CreateDC(safeDriverName.AsBSTR(), safePrinterName.AsBSTR(), NULL, NULL))
{
throw . . .
}
// as I finish with the CDC
dc->DeleteDC();
delete dc;
Run Code Online (Sandbox Code Playgroud)
我需要delete dc后dc->DeleteDC();?
谢谢
由于您dc在堆上分配,是的,您确实需要删除dc.不仅如此,如果你按照你的方式保留代码,你也应该delete dc在抛出之前有一个代码.该DeleteDC功能与分配的内存无关dc.
你可以简化到这个:
// Create a device context for printing
CDC dc;
if(! dc.CreateDC(safeDriverName.AsBSTR(), safePrinterName.AsBSTR(), NULL, NULL))
{
throw . . .
}
// as I finish with the CDC
dc.DeleteDC();
Run Code Online (Sandbox Code Playgroud)
更新:正如@Fred所说,CDC的析构函数会打电话DeleteDC()给你.
我喜欢Brian的回答.但是如果出于某种原因需要动态分配(可能是堆栈空间问题),请使用智能指针.我可能更喜欢boost :: scoped_ptr,但auto_ptr就足够了:
// Create a device context for printing
auto_ptr<CDC> dc(new CDC());
if(! dc->CreateDC(safeDriverName.AsBSTR(), safePrinterName.AsBSTR(), NULL, NULL))
{
// dc is automatically cleaned up on the throw
throw . . .
}
// dc is automatically cleaned up at scope exit
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1196 次 |
| 最近记录: |