我有一些函数需要使用成员变量(自定义类的向量)。
在此功能结束时,需要清除此成员,但它需要在此功能期间保持成员身份。另一个问题是,由于程序的自定义错误处理,该函数可能会提前结束。但是该成员仍然需要清除。
使用Ron 在这篇文章和这篇文章中的建议,我得到了以下代码:
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class A
{
public:
A()
{
m_numbers = { { 3, 1 ,4, 1, 5} };
}
void display()
{
auto cleanNumber = [](decltype(m_numbers)* numbers){
if(numbers)
move(*numbers);
};
auto pClean = std::unique_ptr<decltype(m_numbers), decltype(cleanNumber)>(&m_numbers);
for(int number: m_numbers)
cout << number << endl;
}
private:
vector<int> m_numbers;
};
int main()
{
A a;
a.display();
cout << "should be empty now" << endl;
a.display();
return 0;
}
这给出了以下错误:(对不起格式)
g++ -std=c++17 -o main2 main2.cpp
In file included from d:\program files\minggw\lib\gcc\mingw32\5.3.0\include\c++\memory:81:0, from main2.cpp:3:
d:\program files\minggw\lib\gcc\mingw32\5.3.0\include\c++\bits\unique_ptr.h:
In instantiation of 'std::unique_ptr<_Tp, _Dp>::unique_ptr(std::unique_ptr<_Tp, _Dp>::pointer)
[with _Tp = std::vector<int>; _Dp = A::display()::<lambda(std::vector<int>*)>; std::unique_ptr<_Tp, _Dp>::pointer = std::vector<int>*]':
main2.cpp:20:87: required from here
d:\program files\minggw\lib\gcc\mingw32\5.3.0\include\c++\bits\unique_ptr.h:170:33:
error: use of deleted function 'A::display()::<lambda(std::vector<int>*)>::<lambda>()'
: _M_t(__p, deleter_type())
main2.cpp:16:23: note: a lambda closure type has a deleted default constructor
auto cleanNumber = [](decltype(m_numbers)* numbers){
我想我明白我不能传递这个 lambda 的 decltype,因为默认构造函数被删除。那么如何传递正确的 lambda 删除器呢?
环顾四周,所以我得出了这个似乎等效的答案,但我不明白为什么会这样,以及是什么使我的代码不同?
注意我不确定是否应该编辑我的原始问题。我认为这不是澄清而是寻求进一步的建议,所以我提出了一个新问题,希望符合规则。
你需要传递cleanNumber
到unique_ptr
构造函数:
auto pClean = std::unique_ptr<decltype(m_numbers), decltype(cleanNumber)>(&m_numbers, cleanNumber);
此外,您的 lambda 不会像move(*numbers);
什么一样清除矢量内容。你应该写numbers->clear();
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句