未定义 Lambda 复制分配运算符

Lambda copy assignment operator is not defined

本文关键字:运算符 分配 复制 Lambda 未定义      更新时间:2023-10-16

为什么这不能用CLang 7及更低版本编译,而是用CLang 8及更高

版本编译:
#include <map>
#include <string>
typedef std::map<std::string, int> TestMap;
TestMap m {
    {"a", 1},
    {"b", 2},
    {"c", 3},
};
auto func = [](const TestMap::value_type & p) -> int { return p.second; };
auto func1 = func;
//In CLang 7 and lower copy assignment operator is not defined
func = func1;

到底发生了什么变化?

但这适用于所有 CLang 版本:

auto func1 = []() { return 5;};
decltype(func1) func2 = func1;
func2 = func1;

此处提供的所有示例代码

λ之间有什么区别?

正如@rafix07评论中提到的,您必须使用 C++20 标准进行编译。

C++20 之前的标准:

ClosureType& operator=(const ClosureType&) = delete; (until C++20)

如果未指定捕获,则闭包类型具有默认副本 赋值运算符和默认移动赋值 算子。否则,它有一个已删除的复制赋值运算符(此 包括存在捕获默认值的情况,即使它没有 实际上捕获了任何东西(。(自C++20起(

复制赋值运算符定义为已删除(和移动 未声明赋值运算符(。闭合类型不是 可复制可分配。(至C++20( ClosureType::operator=(const ClosureType&(

ClosureType& operator=(const ClosureType&) = delete; (until C++20)
ClosureType& operator=(const ClosureType&) = default; (since C++20) 
ClosureType& operator=(ClosureType&&) = default; (only if no captures are specified)
ClosureType& operator=(const ClosureType&) = delete; (since C++20) 
(otherwise) 

https://en.cppreference.com/w/cpp/language/lambda

请参阅此处的汇编:https://godbolt.org/z/jpCYNQ

代码示例取自评论中的@Alexey Starinsky 链接。