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

本文介绍了在C++项目中,当智能指针unique_ptr与lambda表达式结合使用时遇到的错误问题。问题源于unique_ptr不支持赋值和拷贝操作,导致编译错误。解决方案包括通过引用传递或改用支持赋值和拷贝的shared_ptr。文章附带了相关资源链接和测试代码以帮助理解。

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.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(){}
    ~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;
}

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值