Effective Modern C++ 32. Use init capture to move objects into closures.

本文探讨了C++中lambda表达式的使用方法及其与move语义的关系。通过具体示例对比了不同版本C++(C++11与C++14)中move捕获的实现方式,并解释了为何move捕获在C++11中被认为是不足之处。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// without using lambda

class Widget {
public:
    bool isValidated() const;
    bool isProcessed() const;
    bool isArchived() const;
};

bool Widget::isValidated() const { return true; }
bool Widget::isProcessed() const { return true; }
bool Widget::isArchived() const { return true; }

class IsValAndArch {
public:
    using DataType = std::unique_ptr<Widget>;
    explicit IsValAndArch(DataType&& ptr) : pw(std::move(ptr)) { }
    bool operator()() const {
        return pw->isValidated() && pw->isArchived();
    }
private:
    DataType pw;
};

auto func = IsValAndArch(std::make_unique<Widget>());
lambda

auto func = [pw = std::move(pw)] { return pw->isValidated() && pw->isArchived(); };

// in C++14

std::vector<double> data;
...
auto func = [data = std::move(data)] { /* uses of data */ };

// in C++11
the absence of move capture was recognized as a shortcoming in C++11;

std::vector<double> data;
...
auto func = std::bind([](const std::vector<double>& data) { /* uses of data */},
    std::move(data));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值