A question about TSharedPtr with Tmap

Hi!

I’ve been reading about smart pointers: Smart Pointers in Unreal Engine | Unreal Engine 5.8 Documentation | Epic Developer Community and Smart Pointers in C++ - GeeksforGeeks . After reading I get confused.

A method has this parameter TMap<int32, TSharedRef<FStar>>& OutStars).

Is it OK to use TSharedRef<FStar> here? Maybe, I can use just a raw pointer.

I don’t know why I’ve started to think that I can’t use TSharedRef here.

Inside this method I do this:

while (PreparedStatement->Step() == ESQLitePreparedStatementStepResult::Row)
{
   TSharedRef Star = MakeShared();

   // Add values to the Star

   // ########################
   // Omitted for brevity
   // ########################

   OutStars.Add(Star->ID, Star);

}

Thanks!

What makes you think that? TMap<int32, TSharedRef<FVector>> compiled for me just fine.

Is there some reason you need it to be a shared reference? Why can’t it just be a TMap<int32, FStar>?

I don’t know. Probably because I have no idea when to use pointers.

Sorry, but I don’t know why I did that. Maybe, because there will be more than 8,000 instances of FStar.

Thanks!

Okay, but creating shared ptrs or references won’t really help with that.

For what you’ve shared, creating a TMap<int32, FStar> would function almost identically to what you already have. Because it’s a TMap, the entries are stable which means that if you add more entries, pointers you may have to keys or values remain valid.

If whatever system owns this map (and is creating the FStars) is handing out pointers to the structure instances, it can just as easily return FStar* as it can TSharedPtr<FStar> or TSharedRef<FStar>. Either way you’re already dealing with a type you can’t use in blueprint, so using the raw structure pointer isn’t more incompatible.

The only case that might be relevant would be that the TSharedPtr/Ref would allow the caller to get the FStar and continue to use it even if it’s been removed from the TMap. If that’s what you’re trying to allow, that’s fine, I don’t know what your expectations are for that TMap changing. But it seems like a weird case, it may not crash (because of the shared pointer) but should other code still be able to use data for a star that no longer “exists”? Only you can really answer that.

Either way, you could simplify it to just an FStar but you shouldn’t really run into any technical issue if you really want the value to be a TSharedRef<FStar>.