Home Cannot create class in AHK after destruction
Reply: 2

Cannot create class in AHK after destruction

Werolik
1#
Werolik Published in 2018-01-11 07:56:26Z

I'm trying to wrap my head around classes in AHK. I'm C++ dev, so would like to make use of RAII (__New, __Delete), but it looks like I miss some concepts since things look very contra-intuitive for me.

After some tries I came up with this simple example:

class Scenario
{
  __New()
  {
    MsgBox, NEW
  }

  __Delete()
  {
    MsgBox, DELETE
  }
}

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

As a result I get the following messages:

  1. NEW
  2. NEW
  3. DELETE
  4. DELETE

Questions:

  1. Why doesn't the object get destroyed during the second assignment? I'd assume the number of refs going to 0, no?
  2. How come I get 2 destructions in a row? Where was that object stored meanwhile? How could scenario variable hold both references?
  3. Why was not the third construction called?
Jim U
2#
Jim U Reply to 2018-01-11 16:19:07Z
  1. Why doesn't the object get destroyed during the second assignment?

Garbage collection had not been triggered yet

I'd assume the number of refs going to 0, no?

References going to 0 does not necessarily trigger GC

  1. How come I get 2 destructions in a row?

Garbage collection cleaned both references at the same time

Where was that object stored meanwhile?

The heap

How could scenario variable hold both references?

scenario does not hold both references

  1. Why was not the third construction called?

Only two Scenario objects are constructed. The variable scenario is a dynamic variable and is not always an instance of the class Scenario. The last assignment scenario := {} just creates an empty object.

Werolik
3#
Werolik Reply to 2018-01-15 10:10:18Z

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'.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.368336 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO