The macros are documented to provide different functionality.
DECLARE_DYNAMIC
:
Adds the ability to access run-time information about an object's class when deriving a class from CObject.
This provides the functionality for introspection, similar to RTTI (Run-Time Type Information) provided by C++. An application can query a CObject
-derived class instance for its run-time type through the associated CRuntimeClass
Structure. It is useful in situations where you need to check that an object is of a particular type, or has a specific base class type. The examples at CObject::IsKindOf
should give you a good idea.
DECLARE_DYNCREATE
:
Enables objects of CObject-derived classes to be created dynamically at run time.
This macro enables dynamic creation of class instances at run-time. The functionality is provided through the class factory method CRuntimeClass::CreateObject
. It can be used when you need to create class instances at run-time based on the class type's string representation. An example would be a customizable GUI, that is built from an initialization file.
Both features are implemented through the same CRuntimeClass
Structure, which may lead to the conclusion that they can be used interchangeably. In fact, code that uses an inappropriate macro will compile just fine, and expose the desired run-time behavior. The difference is purely semantic: The macros convey different intentions, and should be used according to the desired features, to communicate developer intent.
There's also a third related macro, DECLARE_SERIAL
:
Generates the C++ header code necessary for a CObject-derived class that can be serialized.
It enables serialization of respective CObject
-derived class instances, for example to a file, memory stream, or network socket. Since the deserialization process requires dynamic creation of objects from the serialized stream, it includes the functionality of DECLARE_DYNCREATE
.
Put together, the following list should help you pick the right macro for your specific scenarios:
- Use
DECLARE_DYNAMIC
if your code needs to retrieve an object's run-time type.
- Use
DECLARE_DYNCREATE
if, in addition, you need to dynamically create class instances based on the type's string representation.
- Use
DECLARE_SERIAL
if, in addition, you need to provide serialization support.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…