B. Dereij
B. Dereij

Reputation: 45

Giving a std::shared_ptr<std::thread> to itself. Defined or Undefined behavior

I have te following code:

void launchThread() {
    std::shared_ptr<std::thread> t;
    t = std::make_shared<std::thread>([t] {std::cout<< "HelloWorld"<<std::endl;});
    t->detach();
}

int main(){
    launchThread();
    somthing that takes a while.... 
}

If I'm correct the thead should keep itself alive using the shared pointer till the thread itself runs out of scope. But I wonder what happens when the shared pointer gets destructed, will the thread be cleaned properly? Or is this bad practice?

Upvotes: 2

Views: 479

Answers (1)

Vittorio Romeo
Vittorio Romeo

Reputation: 93384

std::thread::detach releases ownership - when the shared_ptr is destroyed nothing will happen to the detached thread of execution.

This is bad practice because you could simply write...

std::thread{[]{ std::cout<< "HelloWorld" << std::endl; }}.detach();

...to spawn a background thread that cleans up after itself.

Upvotes: 4

Related Questions