继承类中的shared_from_this()中的类型错误(是否存在dyn.type-aware共享指针?)

问题描述 投票:3回答:1

我有一个使用'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>双重继承子类吗?

c++ shared-ptr smart-pointers dynamic-cast static-cast
1个回答
2
投票
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_caststd::dynamic_pointer_castis。在投射之前,您不必使用.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
}
© www.soinside.com 2019 - 2024. All rights reserved.