我有一个使用'enable_shared_from_this'的基本View Controller类
class ViewController :
public std::enable_shared_from_this<ViewController>
{ // ...
};
和一个孩子:
class GalleryViewController : public ViewController {
void updateGallery(float delta);
}
问题出现了,当我尝试将我当前的实例传递给第三方(比如lambda函数在某处安排)有一个(罕见的)条件,实例(GalleryViewController)将解除分配,所以我不能直接捕获'this',我需要使用shared_from_this()捕获共享组:
void GalleryViewController::startUpdate()
{
auto updateFunction = [self = shared_from_this()](float delta)
{
return self->updateGallery(delta); // ERROR: ViewController don't have updateGallery() method!
};
scheduler->schedule(updateFunction); // takes lambda by value
}
问题是shared_from_this()返回没有updateGallery()方法的shared_ptr<ViewController>
。
我真的很讨厌在维护噩梦中做dynamic_cast(或者甚至是静态)。代码很难看!
updateFunction = [self = shared_from_this()](float delta)
{
auto self2 = self.get();
auto self3 = (UIGalleryViewController*)self2;
return self3->updateGallery(delta);
};
是否有任何默认模式来解决这个问题?动态类型感知共享指针?我应该用enable_shared_from_this<GalleryViewController>
双重继承子类吗?
void GalleryViewController::startUpdate(bool shouldStart) { if (shouldStart == false) { updateFunction = [self = shared_from_this()](float delta) { return self->updateGallery(delta); // ERROR: ViewController don't have updateGallery() method! }; scheduler->schedule(updateFunction); // takes lambda by value }
问题是
shared_from_this()
返回没有shared_ptr<ViewController>
方法的updateGallery()
。我真的很讨厌在维护噩梦中做dynamic_cast(或者甚至是静态)。代码很难看!
这就是std::static_pointer_cast
和std::dynamic_pointer_cast
is。在投射之前,您不必使用.get()
来获取原始指针。
void GalleryViewController::startUpdate(bool shouldStart)
{
if (shouldStart == false) {
updateFunction = [self = std::static_pointer_cast<GalleryViewController>(shared_from_this())](float delta)
{
return self->updateGallery(delta);
};
scheduler->schedule(updateFunction); // takes lambda by value
}