gpt4 book ai didi

c++ - 对象的 ctor 和 dtor 必须在同一个线程上吗?

转载 作者:太空狗 更新时间:2023-10-29 20:21:16 28 4
gpt4 key购买 nike

在 C++ RAII 中,当对象超出范围时会调用 dtor。多线程机制总是涉及传递回调以在新线程上运行。因此,我认为一个对象不可能在一个线程中构造并在另一个线程中被破坏,因为它们必须是不同的范围。

我说得对吗?或者在某些情况下可以在不同线程中调用对象 ctor 和 dtor?

最佳答案

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?

当然有这种情况(只是日常面包和黄油)。考虑一个简单的生产者/消费者模型和通过队列在线程之间交换的消息实例。

生产者线程创建消息实例并将其插入队列。消费者将其从队列中取出,处理完成后将调用消息析构函数。

关于c++ - 对象的 ctor 和 dtor 必须在同一个线程上吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44976448/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com