unique_ptr的lambda删除器导致编译错误与仿函数

时间:2018-04-25 06:44:03

标签: c++ stl unique-ptr

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

我一直在将我们的代码库从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 =。的

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

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

1 个答案:

答案 0 :(得分:1)

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());