Issue #16788 has been updated by jeremyevans0 (Jeremy Evans).


Unfortunately, I do not know the reason behind the automatic creation of singleton classes for classes.  I'm guessing it is necessary for correct method lookup, but I'm not sure.

Looking at the repository, automatic creation of singleton classes for new classes has been there since one of the earliest commits (1998).  Automatically creating the singleton class of the singleton class when referencing the singleton class of a class is newer, that is in commit:3a5c0bbcb5615b063d32aeee35b4f0f4227fb693.

In terms of the debugger, I created a file (e.g. `t.rb`), containing:

```ruby
ENV["TRACE"] = "1"
c = Class.new
c.singleton_class
```

Then I ran `gdb ruby`, then inside gdb:

```
break class_alloc if getenv("TRACE")
set args t.rb
r
bt
c
bt
c
bt
c
```

----------------------------------------
Bug #16788: T_CLASS counts classes double
https://bugs.ruby-lang.org/issues/16788#change-85146

* Author: ana06 (Ana Maria Martinez Gomez)
* Status: Rejected
* Priority: Normal
* ruby -v: 1.9 to master
* Backport: 2.5: UNKNOWN, 2.6: UNKNOWN, 2.7: UNKNOWN
----------------------------------------
Consider the following code:

``` ruby
h = {}
ObjectSpace.count_objects(h)
puts "Counts: #{ h[:T_CLASS] }, #{ h[:T_ICLASS] }"

objects = []
classes = []
ObjectSpace.each_object(Object){|x| objects << x}
ObjectSpace.each_object(Class){|x| classes << x}

class Test
end

objects2 = []
classes2 = []
ObjectSpace.each_object(Object){|x| objects2 << x}
ObjectSpace.each_object(Class){|x| classes2 << x}

objects_ids = objects.map(&:object_id)
new_objects = objects2.reject { |e| objects_ids.include? e.object_id }

puts "New objects belongs to the classes: #{ new_objects.map(&:class).uniq }"
puts "New classes: #{classes2 - classes}"

h = {}
ObjectSpace.count_objects(h)
puts "Counts: #{ h[:T_CLASS] }, #{ h[:T_ICLASS] }"
```

The result is the following:
```
Counts: 690, 46
New objects belongs to the classes: [Array, Class]
New classes: [Test]
Counts: 692, 46
```

This means that the number of `T_CLASS` is increased by 2 with the creation of 1 class. Why is this the case? Is this a bug?

Consider the slightly modified code with:
``` ruby
class Test
  def self.foo 
  end
end
```
In this case the Singleton class is also created and the results are:

```
Counts: 690, 46
New objects belongs to the classes: [Array, Class]
New classes: [#<Class:Test>, Test]
Counts: 693, 46

```

In this case, `T_CLASS` is increased by 3. So it seems like the issue is only with normal classes and not singleton ones.

From https://stackoverflow.com/questions/61031735
 






-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>