新建/删除和DECLARE_DYNCREATE/DECLARE_DYNAMIC [英] new/delete and DECLARE_DYNCREATE/DECLARE_DYNAMIC

查看:68
本文介绍了新建/删除和DECLARE_DYNCREATE/DECLARE_DYNAMIC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

动态内存分配(new&delete)和动态创建(CObject派生类)之间有什么区别? DMA告诉您在堆上为对象动态创建内存. DECLARE_DYNCREATE动态创建对象...为什么我们使用此宏?他们不相似吗?如果不是,为什么?

What is the difference between dynamic memory allocation (new&delete) and dynamic creation(CObject derived class)? DMA tells that memory is created on heap dynamically for the objects. DECLARE_DYNCREATE creates the objects dynamically...so why do we use this macro? Aren''t they similar? If not, why?

推荐答案

动态创建是一种在运行时创建类对象的能力,为了有效地做到这一点,我们需要访问该类的(及其基础)类型信息.
通过从CObject派生一个类(并放置必要的宏),我们可以通过CRuntimeClass结构获得此信息.
现在,动态内存是在堆而不是堆栈上分配内存的过程.
Dynamic creation is the ability to create the object of a class at runtime and for doing this effectively we need to access the class''s (and it''s base) type information.
By deriving a class from CObject (and putting the necessary macros) we get this information via CRuntimeClass structure.

Now dynamic memory is the process of allocation memory on the heap rather than on the stack.


通过实现的宏-
您可以使用对象链的默认构造函数
不知道有关链的级别的东西:):
By the implemented macro -
you can use the default constructors of an objects chain
without to know something about the chain''s level :) :
// class CShape : public CObject
// class CCircle : public CShape
// class CRectangle : public CShape

CShape* CYourShapeTool::MakeCopy(CShape* pcSrcShape)
{
  ASSERT(pcSrcShape);

  CShape* pcResShape = STATIC_DOWNCAST(
    CShape, pcSrcShape->GetRuntimeClass()->CreateObject() // Default constuctor's call only
  );
  ASSERT(pcResShape);
  
  // Now you could call the virtual void CShape::Assign(const CShape* pcSrc),
  // overwritten by each class (CShape, CCircle, CRectangle) -
  // to copy the properties (class members) as well:
  pcResShape->Assign(pcSrcShape);
  
  return pcResShape;
}

void TestFunction()
{
  CYourShapeTool cTool;

  CCircle cCircle(10, 10, 5); // Non-default constructor's call
  CCircle* pcCopyCircle = STATIC_DOWNCAST(
    CCircle, cTool.MakeCopy(&cCircle) // Default constructor + Assign
  );
  delete pcCopyCircle;
  pcCopyCircle = NULL;

  CRectangle cRect(20, 20, 50, 50); // Non-default constructor's call
  CRectangle* pcCopyRect = STATIC_DOWNCAST(
    CRectangle, cTool.MakeCopy(&cRect) // Default constructor + Assign
  );
  delete pcCopyRect;
  pcCopyRect = NULL;
}


DECLARE_DYNCREATE是MFC的东西,在几种情况下都会发生,MFC使用CreateObject函数创建相应的类.尝试使用向导创建SDI应用程序,然后查看CYourApp :: InitInstance函数,对其进行调试..,:)
DECLARE_DYNCREATE is MFC stuff, This happens in several scenarios, MFC uses CreateObject function to create the corresponding class. Try creating a SDI application using wizard and see the CYourApp::InitInstance function, debug it.. you will understand.. :)


这篇关于新建/删除和DECLARE_DYNCREATE/DECLARE_DYNAMIC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆