Array of Pointers passed as parameter

 

Hi,


I'm a little confused trying to pass an array of pointers as a parameter of a class constructor.

class MyClass : public CObject {

   public:

   

      Fract             *_fract[2];

      ESTADO_CORREDOR   _estado;

      

      MyClass( Fract* &parFract[], ESTADO_CORREDOR estado ) {

         _fract[0] = parFract[0];

         _fract[1] = parFract[1];

         _estado    = estado;

      }

}

and this is how I create a class in my code:

Fract  *parFract[2];
parFract[0] = (Fract*)fract.list.GetNodeAtIndex( idx );
parFract[1] = (Fract*)fract.list.GetNodeAtIndex( idx + 1 );

*pending = new MyClass( parFract, PENDING );

The program compiles but once executed it arise the following error: 2019.02.27 16:18:20.038 (EURUSD,M5) invalid pointer access in 'Controller.mqh' (102,17)

This line is: *pending = new MyClass( parFract, PENDING );


The fact is that I just need to pass references to the new class and I do not know what's wrong and how to accomplish it.

Does anyone could help me understand the concept of passing array of pointers?


Thanks in advance.

 

You shouldn't use externally instantiated dynamic dependencies because it's going to halt your program the moment one of the gets destroyed. If you absolutely have to use this pattern then you need to take explicit ownership of the object in the class. The best way to implement this is to use one of the object collections that automatically delete the objects it points to when it gets destroyed.

#include <arrays/arrayobj.mqh>




class Foo {
   CArrayObj  m_objects;
public:
   Foo(CArrayObj *objects) {
      // taking ownership of dependencies. the original collection cannot delete pointers
      objects.FreeMode(false);
      m_objects.AssignArray(objects);
   }
  ~Foo() {
      printf("Deleting %d objects from Foo", m_objects.Total());
   }
};


void OnStart()
{
   CArrayObj arr;
   arr.Add(new CObject);
   arr.Add(new CObject);
   
   Foo foo(&arr);
}
 
nicholi shen:

You shouldn't use externally instantiated dynamic dependencies because it's going to halt your program the moment one of the gets destroyed. If you absolutely have to use this pattern then you need to take explicit ownership of the object in the class. The best way to implement this is to use one of the object collections that automatically delete the objects it points to when it gets destroyed.

Thanks for your clarification...

I will need to change the way I do things.