代码之家  ›  专栏  ›  技术社区  ›  WBuck

唯一,您引用的是已删除的函数

  •  1
  • WBuck  · 技术社区  · 6 年前

    我正试图移动 unique_ptr WriteAsync 方法。这和预期的一样。我现在遇到的问题是将唯一指针的所有权转移到 strand.post 兰达,然后,再把它移到 QueueMessage . 拿一个 std::unique_ptr<std::vector<char>> .

    在这种情况下,简单的方法是使用 shared_ptr . 我想知道有没有办法不用 .

    // Caller
    static void DoWork( char const* p, int len  )
    {
         client.WriteAsync( std::make_unique<std::vector<char>>( p, p + len ) );
    }
    
    // Callee
    void TcpClient::WriteAsync( std::unique_ptr<std::vector<char>> buffer )
    {
        _strand.post( [ this, buffer = std::move( buffer ) ]( ) 
        { 
            // Error on this line.
            QueueMessage( std::move( buffer ) ); 
        } );
    }
    
    
    void TcpClient::QueueMessage( std::unique_ptr<std::vector<char>> buffer )
    {
         // Do stuff
    }
    

    我看到的错误是:

    您引用的是已删除的函数

    1 回复  |  直到 6 年前
        1
  •  7
  •   Praetorian Luchian Grigore    6 年前

    lambda的函数调用运算符是 const std::move(buffer) 会回来的 std::unique_ptr<std::vector<char>>> const&& ,与已删除的 unique_ptr instead of its move constructor ,因此出现错误。

    要修复错误,请将lambda mutable operator()() 非- ,允许您移动构造 buffer

    [ buffer = std::move( buffer ) ] ( ) mutable 
    //                                   ^^^^^^^
    {
       QueueMessage( std::move( buffer ) );
    }