Skip to content

RefCounted releases itself if it is referenced in NOTIFICATION_POSTINITIALIZE #108395

@beicause

Description

@beicause

Tested versions

4.5

System information

Linux

Issue description

See godot-rust/gdext#1211 (comment)

In GDExtension, referencing RefCounted in postinitialize will cause the count not to increase correctly. The reference count is lower than expected by 1, leading to releasing itself.

This also occurs in constructor.

Steps to reproduce

Run https://github.com/godotengine/godot-cpp-template with following code:

#include "example_class.h"

void ExampleClass::_bind_methods() {
	godot::ClassDB::bind_method(D_METHOD("print_type", "variant"), &ExampleClass::print_type);
}

void ExampleClass::_notification(int p_what) {
	if (p_what == NOTIFICATION_POSTINITIALIZE) {
		UtilityFunctions::print("refcount: ", get_reference_count());
		Ref<ExampleClass> a = this;
		UtilityFunctions::print("refcount: ", get_reference_count());
		Ref<ExampleClass> b = this;
		UtilityFunctions::print("refcount: ", get_reference_count());
		Ref<ExampleClass> c = this;
		UtilityFunctions::print("refcount: ", get_reference_count());
		Ref<ExampleClass> d = this;
		UtilityFunctions::print("refcount: ", get_reference_count());
	}
}

void ExampleClass::print_type(const Variant &p_variant) const {
	print_line(vformat("Type: %d", p_variant.get_type()));
}
extends Node


func _ready() -> void:
	var example := ExampleClass.new()
	example.print_type(example)

Output:

refcount: 1
refcount: 1
refcount: 2
refcount: 3
refcount: 4
SCRIPT ERROR: Cannot call method 'print_type' on a null value.
          at: _ready (res://example.gd:6)
          GDScript backtrace (most recent call first):
              [0] _ready (res://example.gd:6)

Minimal reproduction project (MRP)

See above

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions