程序库: CDictionary - 页 2

 

我在 CDictionary 中发现了一个错误。当您使用重置方法时,它会删除 m_data 中的CList 对象。随后调用其他方法从字典中获取点时,会返回一个坏指针。举例说明:


#include "Dictionary.mqh"

void OnStart()
{
   CDictionary d;
   d.Set("key", 1);
   d.Reset();
   Print(d.Contains<int>("key"));
}


我建议对所有使用 key hash 从 m_data 数组访问 CList 对象的方法进行以下修复。


template<typename T>
bool CDictionary::Contains(string key)
  {
   bool res=false;
   T value=NULL;
   int index=Index(Hash(key+typename(T)));
   if(CheckPointer(m_data[index]) == POINTER_INVALID)
      m_data[index] = new CList;
   CList *list=m_data[index];
   if(CheckPointer(list))
     {
      CDictionaryEntryBase *model=new CDictionaryEntry<T>(key,value);
      if(CheckPointer(list.Search(model)))
         res=true;
      delete model;
     }
   return res;
  }
 
nicholi shen:

我在 CDictionary 中发现了一个错误。当您使用重置方法时,它会删除 m_data 中的 CList 对象。随后调用其他方法从字典中获取点时,会返回一个坏指针。例如



我建议对所有使用键散列从 m_data 数组访问 CList 对象的方法进行以下修复。


感谢 Nicoli shen。你的解决方案是比较 "安全 "的。不过,我无法重现这个问题。

m_data 是一个动态数组,因此当检索数组中未填充的索引或删除存储的项目时,它应该返回空值。在其他方法(如 Get() 和 Delete())中,也会在未事先检查 指针的情况下将 m_data 中的数据存储到 CList* 中,因此如果存在这个问题,上述测试脚本也会失败。在一个指针和另一个指针之间进行简单赋值不会出现任何指针访问错误,即使 lvalue 指向的对象已被删除:

#include <Object.mqh>
//+------------------------------------------------------------------+
//| 脚本程序启动功能|
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   CObject *obj = new CObject();
   delete obj;
   CObject *obj1 = obj; //无无效指针访问错误
  }
//+------------------------------------------------------------------+

这个问题可以简化为上面的示例。但在这种情况下,不会出现指针错误。我很好奇,因为我记得在早期版本中遇到过同样的问题,但很快就打了补丁。

我目前使用的是 MT5 版本 1932,如果我遗漏了什么,请告诉我。

[删除]  

我有这些错误:


'键'--意外标记,可能类型丢失? Dictionary.mqh 39 23

'Key'-函数已定义且类型不同 Dictionary.mqh 39 23

请参阅 "CDictionaryEntryBase::Key "的声明 Dictionary.mqh 20 22



尝试在 3320 版本上运行

 
Sunfire #:

我有这些错误:


Key' - unexpected token, probably type is missing? Dictionary.mqh 39 23

Key' - 函数已定义且类型不同 Dictionary.mqh 39 23

参见 "CDictionaryEntryBase::Key "的声明 Dictionary.mqh 20 22



尝试在 3320 版本上运行

尝试在类方法前添加关键字 "void
 
该代码演示了出色的功能,并利用CObject 继承,实现了与字典中 CArray 结构的无缝集成。
 
用于向字典中添加整数数组:
#include "Include\Dictionary.mqh"
#include <Arrays\ArrayInt.mqh>
/

//+------------------------------------------------------------------+
//||
//+------------------------------------------------------------------+
int OnInit()
  {
//---

   CDictionary my_dict;
   
   //--- 在字典中添加 arrayint
   CArrayInt *my_arr_int= new CArrayInt;
   my_arr_int.Add(10);
   my_arr_int.Add(30);
   my_arr_int.Add(45);
   my_dict.Set<CObject*>("arrayint", my_arr_int);
   
   CArrayInt *res_arr;
   res_arr= my_dict.Get<CObject*>("arrayint");
   Print("intarray at 1= ",res_arr.At(1));
//---
   return(INIT_SUCCEEDED);
  }