Download

How to have a struct with reference to int?

I want to have a struct which has a reference to an int32, so that the actual int32 variable (no matter where it came from in the code) can be altered, not a copy of it. Since you cannot use pointers with int32 (it would be great if you could, because that would immediately solve the problem), I need to use a reference. But I cannot figure out how to set this up, in terms of initialisation.

The basic struct looks like this:


USTRUCT(BlueprintType)
struct FReferenceInt
{
    GENERATED_USTRUCT_BODY()

    UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
    int32& IntReference;

    int32 TempValue = 0;

    FReferenceInt()
    {
        IntReference = TempValue;
    }

    FReferenceInt(int32 IntRef) : IntReference(IntRef) {};
}

When I create the struct I want to pass an int32 into it as a reference. The above won’t compile, and I don’t know how to get it working. I put the TempValue in there because it needs a default constructor, but the default constructor complains “there is no initializer for reference member IntReference”.

How can I have a reference to an int32 in a struct, such that I can manipulate the actual int32 from within the struct?

You can use pointers with int32, but the problem is you can’t use it with blueprints (which don’t have the best pointer support) - also you could run into issues where you are pointing at an integer in some object that gets cleaned up (so now you’re pointing to junk, or worse - invalid memory ).

I would rethink your approach to whatever you are trying to do here.

Ah, OK thanks!

I think you’re right that there’s a better way to accomplish what I’m doing.