Why should I replace raw pointers with TObjectPtr?

TObjectPtr can represent a reference as a handle. That means it opens some options for lazy loading (but editor only, packaged game remains unchanged). When this TObjectPtr/FObjectPtr is seen it does not necessarily need to be resolved at the same time. It can be kept around as a handle and resolved later, when really needed.

Look for LazyOnDemand and TODO: OBJPTR in the engine source. It seems to be tied to TObjectPtr.

In 5.0, USoundWaves have meta=(LoadBehavior = “LazyOnDemand”)
I saw it used also for data assets and other classes in ue5-main branch.

I don’t think it changes initialization in any way. UE5 has a different, more verbose check for uninitialized pointers but it is not related to TObjectPtr. It is used even if you use standard pointers.

It seems using TObjectPtr can lead to better editor time experience like faster asset loads.

TODOs reveal also some potential future work:

// @TODO: OBJPTR: Investigate TObjectPtr support for UFunction parameters.

// @TODO: OBJPTR: we want to permit lazy background loading in the future
// else if (*LoadBehaviorMeta == "LazyBackground")
// {
// 	LoadBehavior = EImportLoadBehavior::LazyBackground;
// }

// @TODO: OBJPTR: Need to find other options for solving this issue of placeholder classes during blueprint compile without forcing all imports to resolve always

// @TODO: OBJPTR: We should have a test that ensures that lazy loading of an object with an external package is handled correctly.

... and many more
3 Likes