Automatic cast to bool

TSharedPtr also implements a cast operator to bool which does the same thing as IsValid.

This means that it is not necessary to call IsValid to check the pointer, you can just compare it as if it was a raw pointer. The following two lines are identical:

if (SessionInterface.IsValid()) ...

if (SessionInterface) ...

The rest is a matter of preference, like when checking for nullptr. Some people prefer if (Ptr != nullptr), while others prefer if (Ptr) (and their counterparts if (Ptr == nullptr) vs if (!Ptr)).

–

Of related interest, the C++ core guidelines, which tries to standardized the way to use and write C++ to avoid common mistakes, recommends the shorter version:

if (Ptr)
if (!Ptr)
1 Like

IsValid is not a nullptr check.

IsValid | Unreal Engine Documentation

Test if this points to a live UObject . What that means, is that is checking to ensure it has not been handled/cleaned up by the Garbage Collection in Unreal Engine as well as being nullptr. Checking for nullptr alone wouldn’t suffice in this case as a non-nullptr object could be disposed of.

Don’t confuse this with std::shared_ptr from the STL - this is the UE Implementation of a similar thing and IsValid call is actually correct.

Same to you :wink: : don’t confuse TSharePtr (and its weak version TWeakPtr) with TWeakObjectPtr.

  1. TSharedPtr (and TWeakPtr) is specifically for non-UObjects and thus not subject to garbage collection.
  2. TWeakPtr and TWeakObjectPtr do not have an operator bool function to cast to bool anyway, so IsValid is the only option (and STL’s std::weak_ptr is in the same boat with the expired function).
    For that matter, typically, one shouldn’t check if a weak pointer itself is valid or not anyway. Most of the time, to avoid race conditions, one should first Pin (or lock for STL std::weak_ptr) the weak pointer to get a shared pointer, which then should be checked for validity. It’s only if one doesn’t want to get a shared pointer out of the weak pointer that checking the weak pointer itself is useful, but that’s much rarer in my experience.

Anyways, this is the code for TSharedPtr:

	/**
	 * Checks to see if this shared pointer is actually pointing to an object
	 *
	 * @return  True if the shared pointer is valid and can be dereferenced
	 */
	FORCEINLINE explicit operator bool() const
	{
		return Object != nullptr;
	}

	/**
	 * Checks to see if this shared pointer is actually pointing to an object
	 *
	 * @return  True if the shared pointer is valid and can be dereferenced
	 */
	FORCEINLINE const bool IsValid() const
	{
		return Object != nullptr;
	}

So yes indeed, TSharedPtr::IsValid is just a nullptr check.

I stand corrected. I still stand by the fact that using implicit conversions is not the best for code readability and so I would still recommend using IsValid() as a good coding practice as far as Unreal Engine is concerned.

It is of course a subjective opinion.

Privacy & Terms