1

我正试图围绕 AHK 的课程。我是 C++ 开发人员,所以想使用 RAII ( __New, __Delete),但看起来我错过了一些概念,因为事情对我来说看起来非常违反直觉。

经过一些尝试,我想出了这个简单的例子:

class Scenario
{
  __New()
  {
    MsgBox, NEW
  }

  __Delete()
  {
    MsgBox, DELETE
  }
}

scenario := new Scenario
scenario := new Scenario
scenario := 1
scenario := {}
scenario := new Scenario
Return

结果,我收到以下消息:

  1. 新的
  2. 新的
  3. 删除
  4. 删除

问题:

  1. 为什么在第二次分配期间对象没有被销毁?我假设裁判的数量将变为 0,不是吗?
  2. 我怎么会连续2次破坏?同时该对象存储在哪里?scenario变量如何同时保存两个引用?
  3. 为什么不调用第三个结构?
4

2 回答 2

0
  1. 为什么在第二次分配期间对象没有被销毁?

垃圾回收尚未触发

我假设裁判的数量将变为 0,不是吗?

指向 0 的引用不一定会触发 GC

  1. 我怎么会连续2次破坏?

垃圾收集同时清理了两个引用

同时该对象存储在哪里?

场景变量如何同时保存两个引用?

scenario不包含两个引用

  1. 为什么不调用第三个结构?

仅构造了两个 Scenario 对象。该变量scenario是一个动态变量,并不总是类的实例Scenario。最后一个分配scenario := {}只是创建一个空对象。

于 2018-01-11T16:19:07.573 回答
0

Ok, found out what was missing. Two things:

  1. AHK script is case-insensitive.
  2. Since class is an object by itself in AHK it's possible to override the class by another object.

Here is a piece of the documentation:

Because the class is referenced via a variable, the class name cannot be used to both reference the class and create a separate variable (such as to hold an instance of the class) in the same context. For example, box := new Box would replace the class object in Box with an instance of itself. [v1.1.27+]: #Warn ClassOverwrite enables a warning to be shown at load time for each attempt to overwrite a class.

This explains what happened in the code above: variable name scenario is effectively the same as a class name Scenario, so I just quietly overrode my class with an empty object.

Also, since the new instance of the class is created before assignment, I got two 'NEW' in a row, only than 'DELETE'.

于 2018-01-15T10:10:18.723 回答