TSharedRef, TSharedPtr - When needed?

Hello, Let’s say I have a simple custom class named FBarData not deriving from anything with some properties of primitive types. There is another class with let’s say a TArray of FBarData. Instances of FBarData will be created by the second class, pushed to the array, sometimes returned by some functions, and of course, destroyed. Classic scenario.

Now what I have learned by looking up much code and intensively reading documentation that using TSharedXxx is easy, simple and I do not have to worry about anything but weather.

So do I have to use TSharedXxx for every instance of my non UObject class? Can I or should I in some cases just do:

FBarData Data = FBarData();

and store such objects in my array? Will it give any benefits or maybe cause errors?

I am very confused because I come from a language where you just created instances by calling new and destroyed them by null’ing references.

Thank you for all the help!

Thank you for straight answer. Can I use TSharedRef instead? I’ve read TSharedRef should be used unless TSharedPtr is a must. Is it a must in this situation? Is there a scenario where I don’t need to use Smart Pointers except for local function code?

Hello, Kosmo

Please note that creating your Object without TSharedPtr in this situation isn’t appropriate.
For correct behavior, please use something like this:

CustomArray[i] = TSharedPtr<FBarData>(new FBarData());

Hope this helped!

Cheers!

You can use TSharedRef, but please keep in mind that, like native C++ references, they are not nullable. This limitation actually makes your code safer, since they are always valid.

However, you can use TWeakPtr and IsValid() method to prevent possible errors.

Thus, this decision depends on your requirements.

As in general, Smart Pointers should be used unless you are capable of handling object destruction with explicit destructor calls (which is actually an error-prone approach in most cases).

Alright thank you!