gpt4 book ai didi

c++ - shared_from_this 与派生类

转载 作者:行者123 更新时间:2023-11-30 03:33:20 27 4
gpt4 key购买 nike

我正在尝试使用 shared_from_this 函数创建指向 this 的共享指针。

#include <iostream>
#include <memory>

class foo {
public:
virtual void method() {
std::cerr << "foo::method()" << std::endl;
}
};

class foo_derived : public foo, public std::enable_shared_from_this<foo> {
public:
void method() override {
auto self(shared_from_this());
std::cerr << "foo_derived::method" << std::endl;
}
};

int main() {
foo_derived().method();
}

此代码从 auto self(shared_from_this()); 行抛出 bad_weak_ptr我认为问题在于 self 是在派生类中创建的。我正在寻找对此行为的解释,也希望看到一个有效的 shared_from_this 用法与派生类的示例。

最佳答案

与继承无关。调用method这种方式反而会起作用:std::make_shared<foo_derived>()->method();

cppreference std::enable_shared_from_this::shared_from_this

It is permitted to call shared_from_this only on a previously shared object, i.e. on an object managed by std::shared_ptr. Otherwise the behavior is undefined (until C++17)std::bad_weak_ptr is thrown (by the shared_ptr constructor from a default-constructed weak_this) (since C++17).

关于c++ - shared_from_this 与派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43045956/

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