实例化一个指针并将其传递给两个队列以供两个线程使用?
Instantiating a pointer and passing it to two Queues to be consumed by two Threads?
我有一些代码,其中线程回调有效地生成一些数据并将其写入队列以供另一个线程使用,看起来像这样
auto data_ptr = std::make_shared<DataFrame>();
data_queue_.write(std::move(data_ptr));
我知道这样写是为了避免从队列中读取和写入时出现副本。我需要实例化另一个线程来使用这些数据并对其进行一些处理。做这样的事情是否合乎逻辑
# Adding this
custom_queue_.write(std::move(data_ptr));
这是否意味着只有当对象从从该队列读取的两个线程中被拉出时才会被删除,然后只有分配的 data_ptr 内存被删除?
Does that mean that the object only gets deleted when it gets pulled out of both of the threads reading from this queue and then only the data_ptr memory allocated gets deleted?
不,不是。第一次使用 std::move
将 'rob' data_ptr
第二次实际上是 UB.
不要害怕复制 std::shared_ptr
。这是一个廉价的操作,不会复制底层数据。事实上,这就是 std::shared_ptr
背后的整个想法 - 共享它所指向的任何内容的所有权,当最后一个 shared_ptr
超出范围时删除对象。
如果你 非常 担心性能(我不是)那么你可以按值将 data_ptr
传递给 data_queue_.write
(从而使copy) 并通过引用到 custom_queue_.write
(因此不制作副本)。在这两种情况下,std::move
都不合适或有用。
但是这样的代码很脆弱。我强烈建议您保持简单,并在这两种情况下按值传递 data_ptr
。这就是 shared_ptr
的用法。人们不会无缘无故地谈论具有值语义的现代 C++。
我有一些代码,其中线程回调有效地生成一些数据并将其写入队列以供另一个线程使用,看起来像这样
auto data_ptr = std::make_shared<DataFrame>();
data_queue_.write(std::move(data_ptr));
我知道这样写是为了避免从队列中读取和写入时出现副本。我需要实例化另一个线程来使用这些数据并对其进行一些处理。做这样的事情是否合乎逻辑
# Adding this
custom_queue_.write(std::move(data_ptr));
这是否意味着只有当对象从从该队列读取的两个线程中被拉出时才会被删除,然后只有分配的 data_ptr 内存被删除?
Does that mean that the object only gets deleted when it gets pulled out of both of the threads reading from this queue and then only the data_ptr memory allocated gets deleted?
不,不是。第一次使用 std::move
将 'rob' data_ptr
第二次实际上是 UB.
不要害怕复制 std::shared_ptr
。这是一个廉价的操作,不会复制底层数据。事实上,这就是 std::shared_ptr
背后的整个想法 - 共享它所指向的任何内容的所有权,当最后一个 shared_ptr
超出范围时删除对象。
如果你 非常 担心性能(我不是)那么你可以按值将 data_ptr
传递给 data_queue_.write
(从而使copy) 并通过引用到 custom_queue_.write
(因此不制作副本)。在这两种情况下,std::move
都不合适或有用。
但是这样的代码很脆弱。我强烈建议您保持简单,并在这两种情况下按值传递 data_ptr
。这就是 shared_ptr
的用法。人们不会无缘无故地谈论具有值语义的现代 C++。