零、前言
C++11以后增加了新的智能指针和lambda表达式,这两个法宝使用起来很方便,法宝虽然厉害,使用不好也会伤人!这不就被我遇上了!
一、问题
项目中使用智能指针unique_ptr和lambda表达式结合使用时出现下面的问题:
“/work/test/testAutoPtr/main.cpp:24: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = MyPrint; _Dp = std::default_delete]’
for_each(tempVector.begin(),tempVector.end(),[=](int numInt){”
二、原因分析
出现上述原因主要是因为unique_ptr不支持赋值和拷贝操作造成的,可以使用引用的方式传值,也可以改成shared_ptr,它支持赋值和拷贝操作,看三中的测试代码。
有关智能指针的使用可以参考:https://blog.youkuaiyun.com/toby54king/article/details/81271947
有关lambda的使用可以参考:https://zh.cppreference.com/mwiki/index.php?title=cpp/language/lambda&variant=zh-hans
三、测试代码
#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>
using namespace std;
class MyPrint
{
public:
MyPrint(){}