Search code examples
c++multithreadingthread-safetyorder-of-executionmake-shared

When a thread is executing make_shared, can another thread do something to cause a leak of the object that make_shared creates via new?


From Effective Modern C++, Item 21, I learned that one advantage of std::make_shared over new+std::shared_ptr is that code like this

processWidget(std::shared_ptr<Widget>(new Widget), computePriority());

can result in a leaked Widget if computePriority() throws in between new Widget evaluation and the call to std::shared_ptr constructor, wheras in this alternative code that is not possible:

processWidget(std::make_shared<Widget>(), computePriority());

But std::make_shared is itself implemented in terms of new and std::shared_ptr.

So a friend asked me, can anything else, in multithreaded fallacious code, happen in the middle of std::make_shared's execution causing the same effect?

I know little or zero of multithreading, so my question may actually be dumb or nonsense, even though I don't know why.

My intuition tells me that if one thread t1 is executing the second snippet of code, there's no way for another thread t2 to get there, in the middle of the code that t1 is executing. And if more threads are executing the second snippet of code, well every one of them will be working on its own anyway. But again, I'm not sure I'm saying anything sensible.


Solution

  • So a friend asked me, can anything else, in multithreaded fallacious code, happen in the middle of std::make_shared's execution causing the same effect?

    Other things can certainly happen in between std::make_shared allocating memory and creating the std::shared_ptr<Widget>. However, none of those things can cause the pointer to leak, unless something has gone seriously wrong (i.e. the program has UB).

    Any exception that occurs in another thread will only interfere with the control flow in that thread and, at worst, bring down the entire process (at which point the operating system will reclaim the memory). In order to make the pointer leak, the other thread would have to corrupt the stack in the thread that is running std::make_shared, which is not possible unless it does something that produces UB.