Shared pointers are non-intrusive, which means the object does not know whether or not a Smart Pointer owns it. This is usually acceptable, but there may be cases in which you want to access the object as a Shared Reference or Shared Pointer. To do this, derive the object’s class from
TSharedFromThis, using the object’s class as the template parameter.
TSharedFromThis provides two functions,
SharedThis, that can convert the object to a Shared Reference (and from there, to a Shared Pointer). This can be useful with class factories that always return Shared References, or when you need to pass your object to a system that expects a Shared Reference or Shared Pointer.
AsShared will return your class as the type originally passed as the template argument to
TSharedFromThis, which may be a parent type to the calling object, while
SharedThis will derive the type directly from this and return a Smart Pointer referencing an object of that type. The following example code demonstrates both functions:
class FMyBaseClass: public TSharedFromThis<FMyBaseClass>
virtual void RegisterAsBaseClass(FRegistryObject* RegistryObject)
// Access a shared reference to 'this'.
// We are directly inherited from <TSharedFromThis> , so AsShared() and SharedThis(this) return the same type.
TSharedRef<FMyBaseClass> ThisAsSharedRef = AsShared();
// RegistryObject expects a TSharedRef<FMyBaseClass>, or a TSharedPtr<FMyBaseClass>. TSharedRef can implicitly be converted to a TSharedPtr.
class FMyDerivedClass : public FMyBaseClass
virtual void Register(FRegistryObject* RegistryObject) override
// We are not directly inherited from TSharedFromThis<>, so AsShared() and SharedThis(this) return different types.
// AsShared() will return the type originally specified in TSharedFromThis<> - TSharedRef<FMyBaseClass> in this example.
// SharedThis(this) will return a TSharedRef with the type of 'this' - TSharedRef<FMyDerivedClass> in this example.
// The SharedThis() function is only available in the same scope as the 'this' pointer.
TSharedRef<FMyDerivedClass> AsSharedRef = SharedThis(this);
// RegistryObject will accept a TSharedRef<FMyDerivedClass> because FMyDerivedClass is a type of FMyBaseClass.
// This function will accept a TSharedRef or TSharedPtr to FMyBaseClass or any of its children.
Do not call
SharedThis from constructors, since the shared reference is not initialized at that time and will cause a crash or assert.