unique_ptr 的 lambda 删除器导致编译错误 vs 函子

理查德·马西森

感觉像是一个基本问题,但让我很困惑。

我一直在将我们的代码库从 VS2012 更新到 VS2015,我们有一个 unique_ptr 和一个自定义删除器,定义如下:

auto cpcdeleter = []( CP_CONVERT * ptr ) { KillCpConvert( &ptr ); };
unique_ptr<CP_CONVERT, decltype( cpcdeleter )> cpc;

...

cpc = unique_ptr<CP_CONVERT, decltype( cpcdeleter )>( CreateCpConvert(), cpcdeleter );

我在 VS2015 中遇到错误,抱怨删除器具有已删除的赋值运算符,因此无法执行赋值。这个赋值在 VS2012 中运行良好,使用了 operator= 的 R-Value 引用重载。

如果我将删除器定义为函子,则一切正常:

struct CpDeleter 
{ 
  public: 
    void operator()(CP_CONVERT *ptr) const { KillCpConvert( &ptr ); } 
};

现在我完全可以做到这一点,但我非常确定使用 lambda 应该有效。直到最近它才这样做!

有人有主意吗?

编辑:所有模板荣耀中的完整错误

c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1382): error C2280: 'openscheduleretrieve_ldlo::<lambda_b4b428a756e3b5d157dcc5597b762dc5> &openscheduleretrieve_ldlo::<lambda_b4b428a756e3b5d157dcc5597b762dc5>::operator =(const openscheduleretrieve_ldlo::<lambda_b4b428a756e3b5d157dcc5597b762dc5> &)': attempting to reference a deleted function
fileopen.cpp(1625): note: see declaration of 'openscheduleretrieve_ldlo::<lambda_b4b428a756e3b5d157dcc5597b762dc5>::operator ='
c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1378): note: while compiling class template member function 'std::unique_ptr<CP_CONVERT,openscheduleretrieve_ldlo::<lambda_b4b428a756e3b5d157dcc5597b762dc5>> &std::unique_ptr<CP_CONVERT,openscheduleretrieve_ldlo::<lambda_b4b428a756e3b5d157dcc5597b762dc5>>::operator =(std::unique_ptr<CP_CONVERT,openscheduleretrieve_ldlo::<lambda_b4b428a756e3b5d157dcc5597b762dc5>> &&) noexcept'
fileopen.cpp(1640): note: see reference to function template instantiation 'std::unique_ptr<CP_CONVERT,openscheduleretrieve_ldlo::<lambda_b4b428a756e3b5d157dcc5597b762dc5>> &std::unique_ptr<CP_CONVERT,openscheduleretrieve_ldlo::<lambda_b4b428a756e3b5d157dcc5597b762dc5>>::operator =(std::unique_ptr<CP_CONVERT,openscheduleretrieve_ldlo::<lambda_b4b428a756e3b5d157dcc5597b762dc5>> &&) noexcept' being compiled
fileopen.cpp(1626): note: see reference to class template instantiation 'std::unique_ptr<CP_CONVERT,openscheduleretrieve_ldlo::<lambda_b4b428a756e3b5d157dcc5597b762dc5>>' being compiled
阿列克谢

Lambda 不可复制赋值,因此您不能在此处使用赋值:

cpc = unique_ptr<CP_CONVERT, decltype( cpcdeleter )>( CreateCpConvert(), cpcdeleter );

因此,请改为执行以下操作:

auto cpcdeleter = []( CP_CONVERT * ptr ) { KillCpConvert( &ptr ); };
// Initialize your smart pointer with nullptr and the deleter needed
unique_ptr<CP_CONVERT, decltype( cpcdeleter )> cpc(nullptr, cpcdeleter);

...

// Then set the desired pointer
cpc.reset(CreateCpConvert());

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章