【问题标题】:unique_ptr, you're referencing a deleted functionunique_ptr,您正在引用已删除的函数
【发布时间】:2018-08-19 16:04:19
【问题描述】:

我正在尝试将 unique_ptr 移动到 WriteAsync 方法。这按预期工作。我现在遇到的问题是将唯一指针的所有权移动到strand.post lambda,然后再次将其移动到QueueMessageQueueMessage 接受std::unique_ptr<std::vector<char>>

在这种情况下,对我来说最简单的方法就是使用shared_ptr。我想知道是否有办法在不使用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
}

我看到的错误是:

您正在引用已删除的函数

【问题讨论】:

  • 您遇到了“...问题...”:它们是什么,错误消息等?
  • 您为什么使用unique_ptrvector?这看起来至少很奇怪,几乎不需要动态分配std::vector
  • 你得到什么错误信息,QueueMessage的声明是什么?
  • 同意@UnholySheep,但是为了更好地探索所提出的问题,我们可以得到minimal reproducible example吗?制作 MCVE 将导致面部手掌并自行修复的可能性很大,但游戏正在回答问题,胜利就是胜利。
  • @WBuck A std::vector 在自身内部有一个 unique_ptr等价,指向它的数据,因此有一个 unique_ptrstd::vector 有点多余。您可以像使用 unique_ptr 一样 std::movestd::vector

标签: c++ c++14 unique-ptr


【解决方案1】:

lambda 的函数调用运算符是const 成员函数。所以std::move(buffer) 将返回std::unique_ptr&lt;std::vector&lt;char&gt;&gt;&gt; const&amp;&amp;,它与删除的unique_ptr 复制构造函数instead of its move constructor 匹配,因此出现错误。

要修复错误,请将您的 lambda 设为mutable,这将使operator()()const,允许您移动构造buffer

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-02
    • 2022-01-07
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    相关资源
    最近更新 更多