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

版权声明:本文为博主原创文章,转载请注明出处。作者:ISmileLi 博客地址:http://blog.csdn.net/toby54king。 https://blog.csdn.net/toby54king/article/details/81320908

一、项目中使用智能指针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;
}

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

猜你喜欢

转载自blog.csdn.net/toby54king/article/details/81320908