Access Violation When Trying To Create TSharedPtr of (this)Object

// Parse the folders array
const TArray<TSharedPtr>* FolderDescriptors;
if (Tree->TryGetArrayField(TEXT(“folder”), /out/ FolderDescriptors))
{
for (TSharedPtr FolderDescriptor : *FolderDescriptors)
{
TSharedPtr Folder = TSharedPtr(new FSpriterFolder());
Folders.Add(Folder);

		const bool bParsedFolderOK = Folder->ParseFromJSON(TSharedPtr<FSpriterSCON>(this), FolderDescriptor->AsObject(), NameForErrors, bSilent);
		bSuccessfullyParsed = bSuccessfullyParsed && bParsedFolderOK;
	}
}

Heres the code that is creating the Access Violation.

It happens when I try to pass a TSharedPtr to the ParseFromJSON method.

I need to pass the Current Object(FSpriterSCON) to the Folder(FSpriterFolder), how would i do this using Smart Pointers?

You could make your object derive from TSharedFromThis and then use AsShared() to get a shared pointer from, however that relies on your object having been allocated on the heap.

I’d question more why you need to use a shared pointer at all. Would a raw pointer or reference work instead? Keeping a shared pointer to your owner object from within a child object could easily lead to a reference cycle and a memory leak (unless you stored it as a weak pointer).

Thanks for the answer! I was refactoring most of my code to work with Smart Pointers, but then realized that most of my Structs only need to store value types anyways, and the ones that wanted references/pointers to other structs would just have to be removed.

The reason behind this is becuase FSpriterSCON is stored as a UProperty inside of a UObject that gets created by a File Factory.

So everytime that UObject was serialized and then reloaded the pointers/references would be NULL because they cant be UPropertys. Also dont ever try and create a Shared Pointer of a value type that wasnt created on the heap/ or if its a UProperty, cause i guess Smart Pointers and UPropertys dont know about eachother’s reference counts.

Yeah, UPROPERTY and TSharedPtr are two completely separate memory management schemes that should never meet.

Use UPROPERTY for any UCLASS or USTRUCT marked types that either need serialisation or GC references. These use garbage collection to manage their lifetime.

Use TSharedPtr for any pure C++ types that exist outside of the UE4 GC logic. These use reference counting to manage their lifetime.

1 Like

This makes things very clear and understandable, thank you very much!