我需要删除这个对象吗

Do I need to delete this object?

本文关键字:对象 删除      更新时间:2023-10-16

在使用Direct2D的MFC应用程序中,我有非常简单的代码:
//在ctor:

EnableD2DSupport();
m_pBlackBrush = new CD2DSolidColorBrush(GetRenderTarget(), D2D1::ColorF(D2D1::ColorF::Black));  

现在的问题是,我应该在m_pBlackBrush上调用delete吗?如果是,在哪里?我试着在析构函数中调用delete,但我的脸上出现了一个错误,说有写访问违规。有人知道我是应该删除这个画笔还是干脆离开它(这似乎是一个很奇怪的想法)?

此构造函数的签名为:

CD2DSolidColorBrush(
   CRenderTarget* pParentTarget,
   D2D1_COLOR_F color,
   CD2DBrushProperties* pBrushProperties = NULL,
   BOOL bAutoDestroy = TRUE
);

请注意最后一个参数。来自MSDN(CD2DSolidColorBrush::CD2DSolidColorBrush):

b自动销毁
指示对象将由所有者销毁(pParentTarget)。

以下是Direct2D对象正在工作的一个小示例:

CChildView::CChildView() 
: m_pBitmamLogo(NULL), 
  m_pBrushBackground(NULL)
{
}
HRESULT CChildView::_LoadBackgroundBrush(CHwndRenderTarget* pRenderTarget)
{
ASSERT_VALID(pRenderTarget);
// Create and load a Direct2D brush from a "PNG" resource
// NOTE: D2D1_EXTEND_MODE_WRAP repeats the brush's content
m_pBrushBackground = new CD2DBitmapBrush(pRenderTarget, // render target
    IDB_PNG_BACKGROUND,                                 // resource ID
    _T("PNG"),                                          // resource type
    CD2DSizeU(0, 0),
    &D2D1::BitmapBrushProperties(D2D1_EXTEND_MODE_WRAP, 
    D2D1_EXTEND_MODE_WRAP));
return m_pBrushBackground->Create(pRenderTarget);
}
CChildView::~CChildView()
{
// No need to free Direct2D resources
// because they are automatically destroyed by the parent render target 
}

来源:http://codexpert.ro/blog/2016/01/18/easy-png-resource-loading-with-mfc/