This-pointer capture in lambda wrapper around recursive function

前端 未结 1 1979
予麋鹿
予麋鹿 2021-01-14 10:21

I have a class template Wrap with a recursive member function test(int) that I want to pass to an STL algorithm with a lambda (std::

相关标签:
1条回答
  • 2021-01-14 11:00

    I believe this is a bug of GCC 4.7.2. The warning says:

    missing initializer for member 'Wrap<T>::test2(int) [with T = int]::<lambda(int, const int&)>::__this'

    Which means that the compiler recognizes the this pointer is to be captured and the generated closure does contain a pointer for it, but that pointer does not get initialized in the closure's constructor.

    This is confirmed by the fact that attempting to access/change a member variable (which is not present in your example, but can be easily added) causes a run-time error. For instance, this shows no output at liveworkspace.org

    #include <algorithm>
    #include <iostream>
    #include <vector>
    
    template<typename T>
    struct Wrap 
    {
        int test2(int depth)
        {
            m_test++;
            std::vector<int> v = { 0, 1, 2, 3 };
            return depth == 0? 1 : std::accumulate(
                 v.begin(), v.end(), int(0), [=](int sub, int const&) {
                 return sub + /*this->*/test2(depth - 1);
                 });   
        }
    
        int m_test = 0;
    };
    
    int main()
    {
        Wrap<int> w;
        std::cout << w.test2(2) << "\n"; // 1
    }
    

    This code compiles fine with Clang 3.2 and VS2012, which seems to confirm the presence of a bug.

    0 讨论(0)
提交回复
热议问题