vendredi 13 avril 2018

Destroying a shared_ptr member variable in the class destructor using a thread

I am trying to recreate destroying a shared_ptr member variable in the bar class destructor using a thread which I feel may be the reason for a heap corruption. The pointer may outlive the application , so using detach is more desirable. The destructor is not called if detach used, however it works if join.

1) Is it wrong to use reset a smart pointer this way?

2) Why the destructor is not called when std::thread::detach() was used ?

#include <iostream>
#include <thread>
#include <memory>
#include <chrono>

using namespace std;

class foo
{
    public:
    foo(){longcomputation();}
    void longcomputation() 
    { 
        std::cout<<" long computation called \n";
        std::this_thread::sleep_for(std::chrono::seconds(1)); 
    }
};

class bar
{
    public:
    bar(): foo_(std::make_shared<foo>()) {}
    ~bar() 
    {
        std::thread([foo = std::move(foo_)] () mutable
        {
          foo.reset();
          std::cout<<" bar dctor called \n";
        }).detach();  // ==========> works with join however
    }
    private:
    std::shared_ptr<foo> foo_;
};



int main()
{
    bar bar1;
    std::this_thread::sleep_for(std::chrono::seconds(3));
    std::cout << "Exiting\n";
}

Aucun commentaire:

Enregistrer un commentaire