UPROPERTY Macro with TWeakObjectPtr and Garbage Collecting

I know that UPROPERTY Macro prevents UObject classes to release by GC. So UPROPERTY is strong reference.
And TWeakObjectPtr should use for preventing circular reference. So This is weak reference like its name.

So I often use them like this :

// Header
UPROPERTY(BlueprintReadOnly, Category = "My Object")
TWeakObjectPtr<UObject> MyObject;

// Source
MyObject = NewObject<UObject>(this, UObject::StaticClass());

I expected MyObject doesn’t GCed and can check validation by IsValid() Function just in case this object destroyed by another.

But when I had processed by this method, MyObject have GCed after about 45 secs from start.
And I obviously identified that it was destroyed by GC through GEngine->ForceGarbageCollection(true).

I think that TWeakObjectPtr invalidates the strong reference of UPROPERTY.

Then, Does UPROPERTY play role as just reflection to Unreal editor in there?

If so, Is there a method to do validation checking my UObject variable while keep UPROPERTY?

why not check against nullptr to directly check if it’s valid?

I’m guessing FWeakObjectPtr overrides the uproperty
in the doc you can clearly see

TWeakObjectPtr derives from FWeakObjectPtr

FWeakObjectPtr = Most often it is used when you explicitly do NOT want to prevent something from being garbage collected.

If you want to get passed circular dependencies then forward declare your class in your header and include it’s header in your cpp file.

1 Like

Oh, I Should read unreal doc more carefully. :drooling_face:

I thought TWeakObjectPtr is just Smart Pointer regardless of Unreal GC.

Why I hope to do validation checking by smart pointers rather than raw pointers is dangling pointer problem.
If UObject is destroyed in itself by ConditionalBeginDestroy function, the variable saving that’s pointer is invalidated but I can’t differentiate.

Perhaps the solution is to destroy the object explicitly by calling a destruction function and then initializing the variable to nullptr. :grinning:

Thanks for your help !!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.