Download

Make Smart Pointers work with Forward Declarations

Currently, TWeakObjectPtr does not support forward declarations, which can be a bit of a nightmare when creating custom structs that you want to reuse. For example:

// This is a header file included by all classes in the game, container a series of enums, structs etc. Similar to Shootergame.
GESTypes.h



USTRUCT(BlueprintType)
struct FMissionTarget
{
	GENERATED_USTRUCT_BODY()

	// Component we're targeting
	UPROPERTY(BlueprintReadOnly, Category = "Target")
	TWeakObjectPtr<USceneComponent> TargetComponent;

	// Socket on the component we're targeting
	UPROPERTY(BlueprintReadOnly, Category = "Target")
	FName TargetSocket;

	// ID of the mission this target belongs to
	UPROPERTY(BlueprintReadOnly, Category = "Target")
	int32 TargetMissionID;

	// Cached Pointer to the Mission
	UPROPERTY()
	TWeakObjectPtr<const UActiveMission> TargetMissionPtr;

	FMissionTarget()
		: TargetComponent(NULL)
		, TargetSocket(NAME_None)
		, TargetMissionID(-1)
		, TargetMissionPtr(nullptr)
	{}
};


The above code does not allow compilation to occur, because it doesn’t know what ‘UActiveMission’ is (which is a custom UObject class). Using a forward declaration


TWeakObjectPtr<const class UActiveMission> TargetMissionPtr;

still prevents compilation, because it can’t determine the template type as a UObject.

UActiveMission already includes this file and needs to do so, which makes compilation impossible and creates circular dependencies.

Are you sure there isn’t something funkier going on? I’ve been able to forward declare weak object pointer types just fine, and searching for “TweakObjectPtr<class” shows plenty of examples in the engine.

You might need to move your constructor to the cpp since it’s probably expecting the definition there rather than the forward declaration in the TWeakObjectPtr part.