问题描述
我正在尝试将 unique_ptr
移至 WriteAsync
方法.这按预期工作.我现在遇到的问题是将唯一指针的所有权移至 strand.post
lambda,然后再次将其移至 QueueMessage
. QueueMessage
使用 std :: unique_ptr< std :: vector< char>>
.
I'm attempting to move a unique_ptr
to the WriteAsync
method. This works as expected. The issue I'm having is now moving ownership of the unique pointer into the strand.post
lambda, and then, moving it again, into QueueMessage
.QueueMessage
takes a std::unique_ptr<std::vector<char>>
.
在这种情况下,对我来说最简单的方法是只使用 shared_ptr
.我想知道是否有一种方法可以在不使用 shared_ptr
的情况下进行这项工作.
The easy way for me in this case would be to just use a shared_ptr
. I'm wondering if there is a way to make this work without the use of a 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
}
我看到的错误是:
推荐答案
lambda的函数调用运算符是 const
成员函数.因此, std :: move(buffer)
将返回 std :: unique_ptr< std :: vector< char>>>.const&
,它与删除的 unique_ptr
复制构造函数而不是其move构造函数匹配,因此是错误.
A lambda's function call operator is a const
member function. So std::move(buffer)
will return std::unique_ptr<std::vector<char>>> const&&
, which matches the deleted unique_ptr
copy constructor instead of its move constructor, hence the error.
要解决该错误,请使您的lambda 可变
,这将使 operator()()
成为非 const
,从而允许您移动构造 buffer
To fix the error, make your lambda mutable
, this will make operator()()
non-const
, allowing you to move construct buffer
[ buffer = std::move( buffer ) ] ( ) mutable
// ^^^^^^^
{
QueueMessage( std::move( buffer ) );
}
这篇关于unique_ptr,您引用的是已删除的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!