Running method while destroying the object

前端 未结 8 1573
抹茶落季
抹茶落季 2021-01-12 22:49

A few days ago my friend told me about the situation, they had in their project. Someone decided, that it would be good to destroy the object of NotVerySafeClass

相关标签:
8条回答
  • 2021-01-12 23:18

    What you need is a sound ownership policy. Why is the code destroying the object when it is still needed?

    Without more details about the code, a std::shared_ptr would probably solve this issue. Depending on your specific situation, you may be able to solve it with a more lightweight policy.

    0 讨论(0)
  • 2021-01-12 23:27

    (Not to promote bad design) but to answer your two questions:

    ... deny running the methods, if destructor was called already

    You can do this with the solution proposed by @snemarch and @Simon (a lock). To handle the situation where one thread is inside the destructor, while another one is waiting for the lock at the beginning of your method, you need to keep track of the state of the object in a thread-safe way in memory shared between threads. E.g. a static atomic int that is set to 0 by the destructor before releasing the lock. The method checks for the int once it acquires the lock and bails if its 0.

    ... force the destructor to wait, until any running method is over

    The solution proposed by @snemarch and @Simon (a lock) will handle this.

    0 讨论(0)
  • 2021-01-12 23:30

    There is no methods that can be used to prevent this scenario.

    In multithread programming, you need to make sure that an object will not be deleted if there are some others thread still accessing it.

    If you are dealing with such code, it needs fundamental fix

    0 讨论(0)
  • 2021-01-12 23:31

    Why not make use of a mutex / semaphore ? At the beginning of any method the mutex is locked, and the destructor wait until the mutex is unlocked. It's a fix, not a solution. Maybe you should change the design of a part of your application.

    0 讨论(0)
  • 2021-01-12 23:32

    Sounds like a horrible design. Can't you use smart pointer to make sure the object is destroyed only when no-one holds any references to it?

    If not, I'd use some external synchronization mechanism. Synchronizing the destructor with a method is really awkward.

    0 讨论(0)
  • 2021-01-12 23:34

    No. Just need to design the program propertly so that it is thread safe.

    0 讨论(0)
提交回复
热议问题