When to use TSharedPtr over normal object initialization

So i am working with the Online-Subsystem.
We need to create an object of the class ‘FOnlineSessionSettings’ which will be used for the session settings. The way this object is initialised is by creating a TSharedPtr.

TSharedPtr SessionSettings = MakeShareable(new FOnlineSessionSettings());

Why does it need to be a shared-pointer? Why can’t it be like this:

FOnlineSessionSettings SessionSettings = FOnlineSessionSettings();

The shared-pointer will clean itself up from memory if i understand it correctly. But a normal object will too if i go out of scope. So what is the difference between the two in this specific usecase?

Hi there @Melvin_Brink, hope you’re well!

This topic has been moved from International to Programming & Scripting: C++.

When posting, please review the categories to ensure your topic is posted in the most relevant space.

Thanks and happy developing! :slight_smile:

TSharedPtr allows multiple modules/etc to read-from or write-to allocated memory and gives each module/etc a way to ensure the memory isn’t free’d until it’s done with the memory.

It can also be made thread safe, which is an easy way to envision the purpose. Say you have two threads that are both reading from the same memory… How do you know when it’s safe to free the memory? How can each thread ensure the memory isn’t free’d while it’s reading from the memory? In this case, the memory is freed when the reference count reaches 0. That happens when both threads allow their TSharedPtr to go out of scope.

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.