C++ 如何在该模板函数中使用启用\u共享\u?

C++ 如何在该模板函数中使用启用\u共享\u?,c++,c++17,boost-asio,shared-ptr,C++,C++17,Boost Asio,Shared Ptr,我试图在模板函数中使用std::enabled_shared_from_this函数,但在类中从this调用shared_时,我一直收到消息bad_weak_ptr error template<T> class A: public std::enable_shared_from_this <A<T>> { /* some parts in the class */ void Run() { resolver_.asy

我试图在模板函数中使用std::enabled_shared_from_this函数,但在类中从this调用shared_时,我一直收到消息bad_weak_ptr error

template<T>
class A: public std::enable_shared_from_this <A<T>>
{

    /* some parts in the class */
    void Run()
    {
        resolver_.async_resolve(host_, port_, boost::bind_front_handler(&A:on_resolve, this->shared_from_this());
    }
    /* ... */
};
我尝试过std::enable_shared_from_this>::shared_from_this和this->shared_from_this,我没有在类构造函数中调用shared_from_this函数。如果有任何方法可以解决这个错误,请告诉我

您的查询错误。而是传递一个查询参数:

    boost::asio::ip::tcp::resolver::query q{host_, port_};
    resolver_.async_resolve(q,
接下来,您可以使用您喜欢的任何一种绑定方法:

    boost::bind(&A::on_resolve, this->shared_from_this(),
        boost::asio::placeholders::error(),
        boost::asio::placeholders::results())
或者根本不使用绑定:

    resolver_.async_resolve(q,
        [self=this->shared_from_this()](boost::system::error_code ec, boost::asio::ip::tcp::resolver::results_type eps) {
            self->on_resolve(ec, eps);
        }
    );
或使用Beast提供的便利助手:

    boost::beast::bind_front_handler(&A::on_resolve, this->shared_from_this())
现场演示 您的查询是错误的。而是传递一个查询参数:

    boost::asio::ip::tcp::resolver::query q{host_, port_};
    resolver_.async_resolve(q,
接下来,您可以使用您喜欢的任何一种绑定方法:

    boost::bind(&A::on_resolve, this->shared_from_this(),
        boost::asio::placeholders::error(),
        boost::asio::placeholders::results())
或者根本不使用绑定:

    resolver_.async_resolve(q,
        [self=this->shared_from_this()](boost::system::error_code ec, boost::asio::ip::tcp::resolver::results_type eps) {
            self->on_resolve(ec, eps);
        }
    );
或使用Beast提供的便利助手:

    boost::beast::bind_front_handler(&A::on_resolve, this->shared_from_this())
现场演示
在问题中包含完整的错误消息。这是一个输入错误吗?这个引用的当前实例是否由一个有效的共享ptr管理。我同意其他评论者的观点:你的代码中有很多不必要的输入错误。不可能编译的代码。始终尝试包含一个或。请看我的答案,看看它看起来是什么样子。同样,由于打字错误和因为有一条注释,所以出现了我假设您有编译错误的错误。幸运的是,我的答案还显示了如何正确使用std::make_shared和/或shared_from_this。请在问题中包含完整的错误消息。这是一个输入错误吗?这个引用的当前实例是否由一个有效的共享ptr管理。我同意其他评论者的观点:你的代码中有很多不必要的输入错误。不可能编译的代码。始终尝试包含一个或。请看我的答案,看看它看起来是什么样子。同样,由于打字错误和因为有一条注释,所以出现了我假设您有编译错误的错误。幸运的是,我的答案还显示了如何正确使用std::make_shared和/或shared_from_this。仅在旁注中,为了连接,请选择哪个将为您解决问题。第三个代码段应该与第二个相同吗?事实上,你说根本不使用bind,这表明它可能不是,而是来自实时演示的lambda。只是在一个旁注上,为了连接,更喜欢哪个将为你解决问题。第三个代码段应该与第二个相同吗?事实上,你说根本不使用bind,这表明它可能不是,而是来自现场演示的lambda。