FVector initialization

I was a bit stuck on this (complile errors) because I tried to call the constructor with the “new” keyword, I guess its my habbit from Java/C# programming.
I noticed only later that you didn’t use “new” and after some search on Internet, I found out that in C++ “new” is used more sparingly because of its allocation of memory (different to other languages). Also I understood from you that strucs are not used like classes with addresses but are directly used, so this is probably why not to use “new” (please do correct me if I am wrong).

I just thought to share this in case someone runs against this issue.

1 Like

Hi!
Just replying to this to clarify a bit for those interested.

Indeed, new in C++ creates what is called a “pointer”, which points to an address in the computer’s memory. Pointers can be useful, but also comes with explicit memory handling, which can be a bit painful.
I tried it in this project, and it seems that Unreal doesn’t like pointers straight up in varaibles; “cannot have an exposed pointer to this type” is the compiler message.
And I think that’s fair enough, modern C++ uses pointers less and less, as it classically can become a mess. Looking forwards in the curriculum, it seems this will be discussed a bit later in the “Crypt Raider” part.
So, something to look forward to, for the curious!

1 Like

Doesn’t the missing of the “new” keyword allocate the memory in the Stack instead of the Heap, in C++?

Moreover I don’t remember if structs in C++ can be initialized with the new keyword or if they are always tied to the Stack, that would explain why the “new” keyword is not working.

Moreover, what we should really start to do is switching to smart pointers. I don’t know much about them but I remember they are a more memory-safe version of the raw pointers.

Last but not least, about pointers, we should be able to use them in UE. I don’t know if something about this has changed since UE4, but here you can see that pointers are getting used:

:slight_smile:

In order to make use of new FVector() the variable would have to be of a type FVector*, that is it would be a pointer to an FVector.
A new operation doesn’t actually “create a pointer”. what it does is create an instance of an FVector (somewhere in memory and returns a pointer to it that is then assigned to the pointer variable.

Which part of memory it would take a bite from and how they might differ would be far beyond the scope of this course (at least in this early stage)…

Privacy & Terms