4

正如论文P0409R2中提出的那样

我期望 x 的定义从 C++20 中被弃用并且无法编译,但它似乎在 g++ (GCC) 8.1.0 中工作有谁知道我是否做错了什么?

在 Visual Studio 2017 中,由于 y 的定义出现错误而无法编译。错误 C3791:当默认捕获模式为复制 (=) 时,无法显式捕获“this”

Live Code

#include <iostream>

struct  X {
    void  f()
    {
        int  value = 3;

        auto  x = [=] {         // Deprecated from C++20: 
            return  value + g(); 
        };

        auto  y = [=, this] {   // Recommended method from C++20: 
            return  value + g();  // [=] The this pointer will not be captured, so capture with specifying this 
        };
    }

    int g() const
    {
        return  2;
    }
};

int  main()
{
    X().f();
}
4

3 回答 3

4

提案并不意味着采纳。也就是说,通读措辞和示例,它指出:

 [=, this]{ };      // OK, equivalent to [=]

这似乎表明这x是允许的。我也没有看到明确提及这一点已被弃用。它甚至提到了相反的情况:

在接下来的调查中,我们不会考虑弃用,因为我们只对探索长期方向感兴趣,而没有方向的弃用并不是那么有趣。

于 2019-01-06T09:18:55.307 回答
2

首先,这只是一个提议,并不意味着它将成为标准的一部分。其次,C++20 仍在开发中。

现在,即使该提案在 C++20 中被采用,即使编译器实现了它,它也明确表示它不建议弃用旧方法:

在接下来的调查中,我们不会考虑弃用,因为我们只对探索长期方向感兴趣,而没有方向的弃用并不是那么有趣。

好的,看起来它确实会在 C++20 中被弃用。但同样,由于 C++20 标准还不是最终标准,编译器正在实现它,所以 gcc 还没有实现它。

至于VS,2017版好像还没有实现C++17 capture-this-by-value。

于 2019-01-06T09:08:52.793 回答
0

看来这篇论文最终被批准了。在 C++ 20 模式下编译时,您的示例代码会产生不同的警告。例如,使用 GCC 10:

$ g++-10 -c -std=gnu++20 -Wall -o main.o main.cpp
main.cpp: In lambda function:
main.cpp:8:19: warning: implicit capture of ‘this’ via ‘[=]’ is deprecated in C++20 [-Wdeprecated]
    8 |         auto  x = [=] {         // Deprecated from C++20:
      |                   ^
main.cpp:8:19: note: add explicit ‘this’ or ‘*this’ capture

如果我改变开关,警告在别处:

$ g++-10 -c -std=gnu++1z -Wall -o main.o main.cpp
main.cpp: In member function ‘void X::f()’:
main.cpp:12:23: warning: explicit by-copy capture of ‘this’ redundant with by-copy capture default
   12 |         auto  y = [=, this] {   // Recommended method from C++20:
      |                       ^~~~
于 2021-12-31T19:49:19.573 回答