federico-busato / Modern-CPP-Programming

Modern C++ Programming Course (C++03/11/14/17/20/23/26)
https://federico-busato.github.io/Modern-CPP-Programming/
11.91k stars 798 forks source link

Question in Capture List and Classes (07.Basic_Concepts_V.pdf) #97

Closed Dong-kyu-Lee closed 5 months ago

Dong-kyu-Lee commented 5 months ago

Hello federico!

While studying Basic_Concepts_V, I have a question because it is different from my code that "[=] default capture of this pointer by value has been deprecated C++20" in p33.

I set C++ version of this project to C++20.

class A {
private:
    int data = 1;
public:
    void foo() {
        auto lambda = [=]() {return this->Print(); };
        lambda(); // print 1
    }
private:
    void Print()
    {
        cout << data << "\n";
    }
};

This code still allows to access this pointer through default capture [=].

federico-busato commented 5 months ago

Hi @Dong-kyu-Lee, deprecated here means that the compiler issues a warning for that line

warning: implicit capture of 'this' with a capture default of '=' is deprecated [-Wdeprecated-this-capture]
    9 |                 auto lambda = [=]() {return this->Print(); };

you can check the warning message with a simple example https://godbolt.org/z/daYovhb71

Dong-kyu-Lee commented 5 months ago

Thank you for your answer! I didin't know that because there wasn't warning message in my project. I'm using Visual Studio 2019 in Windows.

So I have another question, How can i get that warning message in visual studio as well?

I installed Clang according to this document, but it didin't issue a warning.

federico-busato commented 5 months ago

I did a couple of experiments with MSVC. It raises the warning with the following compiler flags /Wall /W1 /std:c++20. You can see an example here https://godbolt.org/z/bxE5a6s1h. While for clang, you need to set -std=c++20 flag

Dong-kyu-Lee commented 5 months ago

I tried and got the warning message. Thank you!