gpt4 book ai didi

c++ - 在 C++11 中不允许重新定义 lambda,为什么?

转载 作者:IT老高 更新时间:2023-10-28 13:21:24 26 4
gpt4 key购买 nike

例子:

#include <functional>

int main() {
auto test = []{};
test = []{};

return 0;
}

这会在 gcc 4.7.2 中发出以下错误消息:

test.cpp: In function ‘int main()’:
test.cpp:5:13: error: no match for ‘operator=’ in ‘test = <lambda closure object>main()::<lambda()>{}’
test.cpp:5:13: note: candidate is:
test.cpp:4:16: note: main()::<lambda()>& main()::<lambda()>::operator=(const main()::<lambda()>&) <deleted>
test.cpp:4:16: note: no known conversion for argument 1 from ‘main()::<lambda()>’ to ‘const main()::<lambda()>&’

来自标准 5.1.2.3(强调我的):

An implementation may define the closure type differently from what is described below provided this does not alter the observable behavior of the program other than by changing:

— the size and/or alignment of the closure type,

— whether the closure type is trivially copyable (Clause 9)

— whether the closure type is a standard-layout class (Clause 9), or

— whether the closure type is a POD class (Clause 9).

据我所知,这就是我遇到的问题。它试图使用已删除的赋值运算符并失败。我很想知道是否有一个简单的解决方法,以及更广泛地说,允许 lambdas 通常省略复制可构造性的动机是什么。

最佳答案

您似乎认为这两个 lambda 具有相同的类型,但事实并非如此。每个都创建自己的类型:

#include <functional>
#include <type_traits>
#include <iostream>

int main() {
auto test = []{};
auto test2 = []{};
std::cout << std::is_same< decltype( test ), decltype( test2 ) >::value << std::endl;
return 0;
}

将打印 0。当然,你从编译器得到的错误信息在这方面可能会更清楚一点......

关于c++ - 在 C++11 中不允许重新定义 lambda,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18755787/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com