https://www.mql5.com/en/docs/basis/types/object_pointers
The article on “Object Pointers” in the MQL5 documentation explains how object pointers are used in the MQL5 programming language, which is designed for developing trading strategies in the MetaTrader 5 trading platform. Here’s a detailed explanation:
- Dynamic Creation of Objects: MQL5 allows for the dynamic creation of objects of complex types. This is achieved using the
new
operator, which returns an 8-byte descriptor of the created object. In MQL5, these descriptors function similarly to pointers in C++. - Object Descriptors: Unlike C++, the variables that store these descriptors (e.g.,
hobject
in the example) are not actual memory pointers but object descriptors. - Passing Objects in Functions: All objects in MQL5 must be passed by reference when used as function parameters. The documentation provides examples of different ways objects can be passed to functions, including:
- Directly passing an object by reference.
- Passing a pointer to an object by reference.
- Passing an array of objects.
- Passing an array of object pointers.
- Checking Pointers: Before using a pointer, it is essential to check its validity to avoid critical program shutdowns. An invalid pointer can occur if it is set to
NULL
or if the object it points to is destroyed using thedelete
operator. TheCheckPointer
function is used to validate pointers in MQL5. Additionally, the “!” operator (logical NOT) can be used for a quick check, implicitly callingCheckPointer
. - Examples and Use Cases: The article provides examples to illustrate these concepts, including creating objects with and without the
new
operator, passing objects and arrays to functions, and checking pointers for validity.
In summary, object pointers in MQL5 are descriptors that represent dynamically created objects. They are crucial for managing objects, especially when passing them to functions or checking their validity, and they differ from traditional pointers in languages like C++.