Problem typecasting with TSharedRef

I need to typecast a TSharedRef. I copied an example from some of the internal UE4 code, but for reasons that escape me it doesn’t compile. This is my code:



void MyModalWindow::WindowClosedHandler(const TSharedRef<SWindow>& InWindow)
{
	TSharedRef<SBorder> DialogWrapper = StaticCastSharedRef<SBorder>(InWindow->GetContent());

...snip


error C2440: ‘static_cast’ : cannot convert from 'const SWidget *const ’ to ‘SBorder *’ C:\Program Files\Epic Games\4.7\Engine\Source\Runtime\Core\Public\Templates\SharedPointer.h

The routine needs to travel down to a child widget to do some cleanup when the window closes. But the compile fails with an error on the static cast. I’m not really sure I want a static cast here. But other variations I tried also didn’t compile. How do I do this?

That’s some really brittle code, there’s zero RTTI in Slate, so if that Content and any further widgets you attempt to traverse to are not exactly the type you expect, any number of nasty things could happen, probably just a crash though.

You should do your cleanup in the widget being destroyed, use your widgets destructor to clean up anything, there shouldn’t be a reason for the window to need to signal a specific widget that it’s closing. Though if it does, it should have a SLATE_EVENT that those widgets adding themselves to it can hook and listen for, rather than the window widget doing chicanery to inform a specific child of its coming demise.

I’m going to have to agree with Nick. My life has been made a lot easier after I did a pass on our UI widget hierarchy to control the lifespan of widgets. By avoiding holding TSharedPtr references unless absolutely necessary, and just relying on the built-in shared ptr destruction, I’ve pretty much solved all cleanup issues we had.

As for the reason your cast is failing, it’s because SWindow::GetContent returns a shared ref to a const widget, and you are trying to drop the const qualifier in your cast.

There’s not really an issue with getting unexpected types. The custom widget I’m after is the child to the sborder. If it’s not there, then something is seriously wrong elsewhere.

The issue is that if the user clicks on the window frame’s [x] to kill the modal window rather than the cancel button, it leaves things in a bad state. I need to tell the widget to essentially do the cancel stuff when that happens because the code that put the window up in the first place doesn’t get notified otherwise.

But since you seem to have implemented your own modal window class, moving this logic to its destructor (and making sure you don’t hold on to any references to the window) will enable both the cancel and the close button to have the same behaviour of doing cleanup when the window is removed.