Why is TArray.Init(MyClass) calling the Deconstructor of MyClass?

I want to use a TArray to store data of a particular class, but when I use TArray.init, I notice that after it’s done initializing my class, the deconstructor is called. Is there a way around this?

StorageClass.h
    class BASIC_API StorageClass
    {
        StorageClass()
        ~StorageClass()
        MicroClass Data
    }

_
MicroClass.h

class Basic_API MicroClass
{
    TArray<int> MicroData
}

_
Main.cpp

class BASIC_API Main
{
    void Initialize()
    {
        TArray.Init(StorageClass(), 4);
// Deconstructor of Storage class is called after StorageClass Constructor call, why is   // this?
    }
}

This is a simplified version of what my program is storing, but the basics are all there.

I’ve tried using TArray.Add and TArray.SetNum, but for some reason the deconstructor is always called.
Is there a way around this?

SetNum definitely shouldn’t be calling the destructor unless you set it to a smaller number. Double check that it actually compiled when your dtor went off- it tends to lie to me at unexpected times oTL

Init does because you’re creating a temp object on the stack, which is then copied for each element, and the temp object gets destructed; Init also empties out anything that was in the array previously, so those will be destructed. Add just copies another object, so any temps will get dtor’d.

Instead you can use AddDefaulted, AddZeroed, InsertDefaulted, InsertZeroed, etc… Which mass-add items without using a temporary- but they’re only ever default or zero’d- filled with 0 (be careful, not everything works zero’d).

If nothing else works, or you must construct the object for any reason, you can use Reserve + Emplace - and give Emplace the constructor parameters instead of an object. This will reserve the memory ahead of time and construct the objects in-place without copying or moving.

All of that said, and I don’t know your specific use case, but how much does it matter? Most of the time, destructors are cheap and in the majority of cases it’s negligible. Unless you have a strong reason to believe it’s impacting your performance in a meaningful way, it’s probably not worth the worry.

This is everything I needed to see. Thank you. That gave me a much greater understanding of the inner-workings of a TArray. It seems my problem was that I had a pointer to a TArray that wasn’t being updated to the new address of the new TArray.