gpt4 book ai didi

c++ - 在 clang 和 gcc 中移动可分配的 lambda

转载 作者:太空狗 更新时间:2023-10-29 21:15:13 25 4
gpt4 key购买 nike

我有这个程序:

int main()
{
auto l([](){});

::std::cout << ::std::is_move_assignable<decltype(l)>{} << ::std::endl;
}

gcc-6.1.1 显示 0

clang-3.8.0 显示 1

这导致我的程序出现编译错误。哪个编译器是正确的?

错误:

error: object of type '(lambda at t.cpp:5:5)' cannot be assigned because its copy assignment operator is implicitly deleted

但这与我的问题无关。

最佳答案

N4140(大致为 C++14)说:

5.1.2 Lambda expressions [expr.prim.lambda]

20 The closure type associated with a lambda-expression has a deleted (8.4.3) default constructor and a deleted copy assignment operator. It has an implicitly-declared copy constructor (12.8) and may have an implicitly-declared move constructor (12.8). [ Note: The copy/move constructor is implicitly defined in the same way as any other implicitly declared copy/move constructor would be implicitly defined. -- end note ]

请注意,这里没有提及删除的复制赋值运算符是否被隐式声明。编译器将 lambda 转换为类定义和实例化,但可以通过隐式声明复制赋值运算符的方式巧妙地定义该类,但该类的其他一些属性会导致隐式复制赋值运算符被删除。

然后:

12.8 Copying and moving class objects [class.copy]

20 If the definition of a class X does not explicitly declare a move assignment operator, one will be implicitly declared as defaulted if and only if

(20.1) -- X does not have a user-declared copy constructor,

(20.2) -- X does not have a user-declared move constructor,

(20.3) -- X does not have a user-declared copy assignment operator, and

(20.4) -- X does not have a user-declared destructor.

如果 lambda 的复制赋值运算符被隐式声明,它不会抑制移动赋值运算符的生成。如果明确声明,移动赋值运算符将被禁止。

根据标准的文字措辞,这两种行为都是可以辩护的。

CWG issue 1891 部分解决了这个问题,将文本更改为:

The closure type associated with a lambda-expression has no default constructor and a deleted copy assignment operator. It has a defaulted copy constructor and a defaulted move constructor (12.8 [class.copy]). [Note: These special member functions are implicitly defined as usual, and might therefore be defined as deleted. -- end note]

然而,尽管移动赋值运算符在那个问题中被提出来作为一个问题,它并没有改变答案,它继续留下了可能性。

关于c++ - 在 clang 和 gcc 中移动可分配的 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38541354/

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