How to get a TSharedPtr of "this"?

Hello,

since this

struct FTestStruct
{
public:
    TSharedPtr<FTestStruct> TestFunc()
    {
        return TSharedPtr<FTestStruct>(this);
    }
};

// (...)

    TSharedPtr<FTestStruct> a(new FTestStruct);
    TSharedPtr<FTestStruct> b = a->TestFunc();

doesn’t work, is this

struct FTestStruct
{
public:
    TSharedPtr<FTestStruct> self;

    TSharedPtr<FTestStruct> TestFunc()
    {
        return self;
    }
};

// (...)

    TSharedPtr<FTestStruct> a(new FTestStruct);
    a->self = a;

    TSharedPtr<FTestStruct> b = a->TestFunc();

a good way for this?

Thanks

This can create a memory leak as having shared ptr for this in its own object will make that said shared ptr to never go out of scope which mean your object will never be deleted.
If you absolutely want to save this as a smart pointer, store it as weak ptr.
For actual issue, you can mark constructor as private and have a static function like CreateInstance

 struct FTestStruct
 {
 public:
    TSharedPtr<FTestStruct> CreateInstance(){
        TSharedPtr<FTestStruct> instance = MakeShared<FTestStruct>();
        instance->thisWeakPtr = instance;
    }
    TWeakPtr<FTestStruct> GetWeakPtr() const {return thisWeakPtr;}
private:
    FTestStruct() {}

    TWeakPtr<FTestStruct> thisWeakPtr;
 };

Conversely you can look at * TSharedFromThis *.