https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86256

            Bug ID: 86256
           Summary: Lambda will not add ref count for class intelligent
                    pointer member when capture 'this' or & as argument
           Product: gcc
           Version: 5.4.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: kangchuanbo at 126 dot com
  Target Milestone: ---

For example:

#include <iostream>
#include <memory>

class A {
public:
    A(){
        tmp = std::make_shared<int>(1);
    }
    void start() {
        std::cout << "ref count : " << tmp.use_count() << std::endl;
        std::shared_ptr<int> tmp2 = tmp;
        std::cout << "ref count : " << tmp.use_count() << std::endl;
        auto xxfunca = [this]()  { std::cout<<"func1 ref count :
"<<tmp.use_count() << std::endl; };
        std::cout << "ref count : " << tmp.use_count() << std::endl;
        auto xxfuncb = [tmp2]() { std::cout<<"func2 ref count :
"<<tmp2.use_count() << std::endl; };
        std::cout << "ref count : " << tmp.use_count() << std::endl;
        auto xxfuncc = [&]() { std::cout<<"func2 ref count : "<<tmp.use_count()
<< std::endl; };
        std::cout << "ref count : " << tmp.use_count() << std::endl;
    }
private:
    std::shared_ptr<int> tmp;
};

int main()
{
    A a;
    a.start();
    return 0;
}

result and analyse:
[root~]]# ./test
ref count : 1    // tmp init ref count = 1
ref count : 2    // copy to tmp2,tmp ref count will incrase to 2
ref count : 2    // Lambda capture this,tmp ref count no incrase
ref count : 3    // Lambda capture tmp2,tmp ref count incrase to 3
ref count : 3    // Lambda capture &,tmp ref count no incrase

==========
The compiler will not copy class member, may feel too complex to check class
member, but should give warning or error to user when lambda capture Class with
intelligent member, or user may meet null pointer which lead to coredump.
Thanks.

Reply via email to