gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:59:37 25 4
gpt4 key购买 nike

我有一个使用 enable_shared_from_this<> 的 View Controller 基类

class ViewController :
public std::enable_shared_from_this<ViewController>
{ // ...
};

和一个 child :

class GalleryViewController : public ViewController {
void updateGallery(float delta);
}

问题出现了,当我尝试将我当前的实例传递给第 3 方时(比如 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()返回 shared_ptr<ViewController>没有 updateGallery()方法。

我真的很讨厌做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
}

The problem is that shared_from_this() returns a shared_ptr<ViewController> that doesn't have the updateGallery() method.

I really hate to do dynamic_cast (or even static in this case) its the maintenance nightmare. And the code is ugly!

这就是 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
}

关于c++ - 继承类中的 shared_from_this() 类型错误(是否有 dyn.type-aware 共享指针?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47869439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com