Using FCanvas

I’m using an FCanvas in my game to draw some basic shapes into a texture and I’m just wondering what the proper way to use the struct is. All the examples I’ve seen on the Answer Hub and forums use new and allocate the memory manually that way since it seems you can’t have one in a UClass/UStruct because it doesn’t have a default constructor. If you plan on keeping an FCanvas around and updating it each tick is this the intended way of doing it? I was under the impression that you should never use new yourself in UE4 but that seems to be the only way to do this. Or are you not supposed to keep one between ticks and just recreate it every time you need it?

What I’m doing isn’t complicated enough for me to worry about memory leaks but I’d like to use UE4’s memory management instead if possible.

You can use new, in fact you need to in some cases, if you extending editor and for example want to add your own asset time, the Asset type info is keeped in non-UObject class that need to be manually allocated. Just you can’t use it on UObjects which is tied with UE4 memory management.You also need to remember that if you use it you are reponcible to manage it if you allocate and lose pointer without deleting the object first then you got memory leak.

I never used it in FCanvas outside of AHUD class so not sure if this will work, but if you don’t want to deal with memory allocation you could always try delere it staticly:

FCanvas Canvas;

If you do that FCanvas (or any other struct or varable that is not a pointer) becames integral part of class memory structure and it allocated and deallocated together with it, this is safest way to go. Just remember you can’t do that with UObjects

I did try to allocate it statically, but FCanvas doesn’t have a default constructor and I can’t use just default values for it in my object initializer list and reconstruct it once I have the correct parameters since its constructor makes sure I’m not passing in a null pointer.

I did end up just newing it but thanks for the explanation.