![](/img/trans.png)
[英]Shared pointer of a class inside a class referenced by a shared pointer gives error when trying to perform shared_from_this
[英]Wrong type in shared_from_this() in inherited class (is there a dyn.type-aware shared pointer?)
我有一个使用enable_shared_from_this<>
的基本视图控制器类
class ViewController :
public std::enable_shared_from_this<ViewController>
{ // ...
};
和一个孩子:
class GalleryViewController : public ViewController {
void updateGallery(float delta);
}
问题出现了,当我尝试将我当前的实例传递给 3rd 方时(比如要在某处安排 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()
返回一个没有updateGallery()
方法的shared_ptr<ViewController>
。我真的很讨厌做 dynamic_cast (在这种情况下甚至是静态的),这是维护的噩梦。 而且代码很丑!
这就是std::static_pointer_cast
和std::dynamic_pointer_cast
的用途。 您不必在转换之前使用.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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.