Search code examples
c++multithreadingraii

Must an object's ctor and dtor be on the same thread?


With C++ RAII, the dtor gets called when the object goes out of scope. The mechanisms for multithreading always involve passing a callback to be run on a new thread. Thus, I don't think it's possible for an object to be constructed in one thread and destructed in another, since those would have to be different scopes.

Am I right about this? Or are there some cases where an objects ctor and dtor can be called in different threads?


Solution

  • Thus, I don't think it's possible for an object to be constructed in one thread and destructed in another, since those would have to be different scopes.

    Am I right about this?

    No. These functions can be called completely independent of any threading.

    Or are there some cases where an objects ctor and dtor can be called in different threads?

    Sure there are cases (just daily bread and butter). Think about a simple producer / consumer model and message instances exchanged between threads through a queue.

    The producer thread creates the message instance and pushes it into the queue. The consumer takes it off from the queue and the messages destructor will be called after it was processed.