我正在尝试移动 unique_ptr
到 WriteAsync
方法。这按预期工作。我现在遇到的问题是将唯一指针的所有权转移到 strand.post
中。 lambda,然后再次将其移动到 QueueMessage
中.
QueueMessage
需要 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
}
我看到的错误是:
you're referencing a deleted function
最佳答案
lambda 的函数调用运算符是 const
成员函数。所以std::move(buffer)
将返回 std::unique_ptr<std::vector<char>>> const&&
, 匹配删除的 unique_ptr
复制构造函数 instead of its move constructor ,因此出现错误。
要修复错误,请使您的 lambda mutable
,这将使operator()()
非 const
,允许您移动构造 buffer
[ buffer = std::move( buffer ) ] ( ) mutable
// ^^^^^^^
{
QueueMessage( std::move( buffer ) );
}
关于c++ - unique_ptr,你引用了一个已删除的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51919473/