은단연
은단연

Reputation: 19

thread for c++11, create with new

Is it really alright to make thread with new & delete is working properly?

Q1. trying to make new thread by using new is alright?

Q2, Is there no problem delete th after join?

example

class Myclass {

private:
    thread *th;

public:
    ~Myclass(){delete th;};
    void create_thread();
    void thread_func();
};

Myclass::create_thread()
{
    th = new thread(thread_func, this);
    th->join();
}

Myclass::thread_func()
{
    while(1){};
}

Upvotes: 1

Views: 140

Answers (2)

eerorika
eerorika

Reputation: 238281

Q1. trying to make new thread by using new is alright?

Dynamically allocating a thread is OK. However, just because you can, doesn't mean that you should. There is no need or advantage to allocate the thread dynamically in this case.

And it is not "alright" to manually allocate memory willy nilly, in general. There is hardly ever a case for manual memory management. It is hard to do correctly. In fact, it is not done correctly in your class. Consider what happens when it is copied. Bad things will happen.

Q2. Is there no problem delete th after join?

Not only is it OK to delete the pointer, it must be deleted or else you leak memory. The thread must have joined (or detached) before being destroyed. Otherwise the process terminates.

Upvotes: 0

Kahler
Kahler

Reputation: 1140

A1: It's alright, thread is a class. It can be newed and deleted.

A2: No problem. On the contrary, you should call delete after joining the thread. delete calls the object destructor, and destroying a joinable thread calls for terminate on it.

Your example have some major flaws...

  • the pointer is deleted regardless of it's contents, and is not initialized with nullptr, so if you create a MyClass object and destroy it without calling create_thead, you will call delete on an uninitialized pointer.

  • thread_func never returns, so the join never happens, so create_thead never returns.

Upvotes: 3

Related Questions