UPROPERTY and TWeakObjectPtr used together?

As far as I know,
UPROPERTY sets pointed object to added to GC reference graph, and prevent it from garbage collection.

Otherwise, the memory presented by TWeakObjectPtr can’t be prevented from garbage collecting.
Its purpose is similar to a raw pointer but different from using a raw pointer, it can detect the object destroyed.

But recently I found a code and I can’t understand the purpose.

USTRUCT()
    struct FTileSetImportMapping
    {
    	GENERATED_USTRUCT_BODY()
    
    	UPROPERTY()
    	FString SourceName;
    
    	// here
    	UPROPERTY()
    	TWeakObjectPtr<class UPaperTileSet> ImportedTileSet;
    
    	UPROPERTY()
    	TWeakObjectPtr<class UTexture> ImportedTexture;
    };

This code was found in the engine code.
I want to know why UPROPERTY and TWeakObjectPtr are used together.

Hello! The thing is that UPROPERTY macro also used to create metadata for other purposes, especially for serialization and reflection system

So you can judge that that variable was declared for serialization and weak reference?

That’s the perfect answer.
All of your questions have been solved.
Thank you :slight_smile:

You can think of it is a such way:

  • It is weak reference field, so it is not blocking GC
  • Second thing - it is UPROPERTY, so UE know something about this field. It knows that this struct contains this field and calculate size of struct with paying attention to it. Also UE adds special methods and registers all such UPROPERTies for this struct class
1 Like