C++ 智能指针unique_ptr和lambda表达式结合使用问题

C++ 智能指针unique_ptr和lambda表达式

零、前言

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.csdn.net/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(){}
    ~MyPrint(){}

    void myPrint(int num)
    {
        cout << " " << num;
    }
};

int main(int argc, char *argv[])
{
    vector<int> tempVector(6,1);
    unique_ptr<MyPrint> pMyPrint(new MyPrint);

    //(1) pMyPrint指针使用《赋值》方式传入到lambda表达式中,会出现上述一中的错误
//    for_each(tempVector.begin(),tempVector.end(),[=](int numInt){
//        pMyPrint->myPrint(numInt);
//    });

    // (2) pMyPrint指针使用《引用》方式传入到lambda表达式中
    cout << "=======test unique_ptr======" << endl;
    for_each(tempVector.begin(),tempVector.end(),[&pMyPrint](int numInt){
        pMyPrint->myPrint(numInt);
    });

    cout << "\n=======test shared_ptr======" << endl;
    shared_ptr<MyPrint> pPrintf(new MyPrint);
    // (3) pPrintf指针使用《赋值》方式传入到lambda表达式中
    for_each(tempVector.begin(),tempVector.end(),[=](int numInt){
        pPrintf->myPrint(numInt);
    });

    // (4) pPrintf指针使用《引用》方式传入到lambda表达式中
    cout << "\n==============" << endl;
    for_each(tempVector.begin(),tempVector.end(),[&](int numInt){
        pPrintf->myPrint(numInt);
    });


    cout << endl;
    cout << "Hello World!" << endl;
    return 0;
}

运行结果:
这里写图片描述

posted @ 2018-07-31 21:17  ISmileLi  阅读(234)  评论(0)    收藏  举报