why FVector's default constructor function did not set X,Y,Z to zero. it may cause uncentain problem

why FVector’s default constructor function did not set X,Y,Z to zero. it may cause uncentain problem 。

1 Like

What problems are you having, so maybe we can help?

Although Vectors default constructor does not set values to 0:

When I test it with following code:

    FVector TestVector;
    UE_LOG(LogTemp, Warning, TEXT("My Vector: %s"), *TestVector.ToString());

The result response is: "LogTemp: Warning: My Vector: X=0.000 Y=0.000 Z=0.000"

So I would assume that eventhough Vector’s constructor doesn’t set floats to 0, still float’s constructor set it.

Vectors are not initialized.

The default constructor even says so in the comments:

/** Default constructor (no initialization). */
TVector() = default;

Primitive types don’t use their constructors unless explicitly called.

In debug mode, everything is zero initialized if it doesn’t have a constructor, but not in release mode. In release mode, uninitialized variables just have whatever is in memory at the time.

When using FVectors, if you want to initialize them to zero, you have to do it yourself with one of these:

FVector x1 = FVector::ZeroVector;
FVector x2 = FVector::Zero();
FVector x3(0);
FVector x4(0,0,0);
FVector x5(EForceInit::ForceInitToZero);

@xjawaker I’ve been a programmer for a VERY long time and I’ve been caught by this myself a few times. The worst part is that zero is often what’s in memory, so the problem can appear randomly. And it doesn’t show up in debug mode.

edit: Thanks for mentioning this. I just scanned my codebase for my game and noticed a few places, I was returning FVector2d() expecting it to return zero. I’ve updated it to return FVector2d::Zero() instead.

1 Like

Wow that’s great to know, thanks for the whole explanation. It looks like it’s so easy to mess up the code with default FVector :slight_smile:

Is there the same situation with floats that uninitialized float could take random value from memory instead of being 0.0?

Yeah, if you just have the following:

float value;

That’s random data if you read from it afterwards. The compiler usually warns you if you try to use uninitialized primitives though. But it won’t do it for FVector because you’re actually using the default constructor.

Everything? That doesn’t sound right, do you mean UObject members? Can you be more specific on the what and the why?

EVERYTHING that is allocated is zeroed out first in debug mode. If you have constructors, those are called after.

It’s not a UObject or UE thing. It’s a debug mode compiler thing. It is injected directly into all your code. Even stack space is zeroed out. This is so that all variables have a known value. Otherwise, it makes debugging a nightmare.