Losing const qualifier through soft pointer? Hacky?

In a specific situation where I need to access a loaded asset, I could only retrieve a const pointer. Casting away const on a variable and then modifying that variable results in undefined behavior: const_cast conversion - cppreference.com . Instead of const casting I realized I could simply get to the object by first making a soft pointer of the UObject pointer and then getting the asset.

– Hacky? –

	const UObject* A = nullptr;
	TSoftObjectPtr B = TSoftObjectPtr(A);
	UObject* C = B.Get();

It’s only undefined behavior if you’re trying to strip the const-ness from something where that is impossible (like a compile-time constance) or you’re crossing the volitile/non-volitile keyword boundry.

What you’re doing there is really no different than doing a const_cast and since you’re dealing with asset data none of the undefined behavior cases should be relevant.
Const_casts (or this) are always hacky. If you’re in an Editor environment, you should be able to get a non-const version of pointer in a safe manner to modify it. If you’re in a Game enviromment, it’s not a good idea to modify the asset as you’ll lose all those modifications when the asset is unloaded (and other potentially weird behavior in PIE sessions).

1 Like

Thanks! Learnt about the volatile keyword today, and the difference between a compile-time and runtime constant.

Since assets can’t possibly be known during compile time any reference to them has to be made runtime. It’s tricky to figure out where the original reference came from but since UObjects are made using the method “NewObject” which returns a non const value We can safely assume that const_cast can be used on UObjects? I am indeed only doing so within the editor but I simply want to make sure it doesn’t turn the pc into a toaster :slight_smile: .

I wouldn’t say that because of the method of allocation exactly it’s safe, but more or less. UObjects are so complicated that’s it’s impractical to have one as a compile time constant in a manner that would cause you issues with a const_cast.

Still, if there’s another way for you to get that pointer as a non-const one, it might be better.

1 Like

I wish :slight_smile: . I have an FDataTableRowHandle which contains a datatable but it is const. The problem with that is that I can’t listen to modification of that datatable through a delegate because it is const. Currently I used const_cast to do it.