使用 sizeof(boost::lockfree::queue<std::string>) 时出错

Posted

技术标签:

【中文标题】使用 sizeof(boost::lockfree::queue<std::string>) 时出错【英文标题】:an error while use sizeof(boost::lockfree::queue<std::string>) 【发布时间】:2021-08-11 11:32:32 【问题描述】:

我收到有关 sizeof(boost::lockfree::queuestd::string) 的错误。我的代码如下:

全球.h:

extern boost::lockfree::queue<std::string> &imgPendingQueue;

class Initializer

// do something
;

全球.cpp:

#include "Global.h"

static char imgPendingQueueBuf[sizeof(boost::lockfree::queue<std::string>)];

boost::lockfree::queue<std::string> &imgPendingQueue = reinterpret_cast<boost::lockfree::queue<std::string>&>(imgPendingQueueBuf);

// do something

编译时出现错误:

/usr/local/include/boost/lockfree/queue.hpp:95:5: error: static_assert failed due to requirement 'boost::has_trivial_destructor<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>>::value' "(boost::has_trivial_destructor<T>::value)"
    BOOST_STATIC_ASSERT((boost::has_trivial_destructor<T>::value));
    ^                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/local/include/boost/static_assert.hpp:70:41: note: expanded from macro 'BOOST_STATIC_ASSERT'
#     define BOOST_STATIC_ASSERT( ... ) static_assert(__VA_ARGS__, #__VA_ARGS__)
                                        ^             ~~~~~~~~~~~
Global.cpp:8:32: note: in instantiation of template class 'boost::lockfree::queue<std::__1::basic_string<char>>' requested here
static char imgPendingQueueBuf[sizeof(boost::lockfree::queue<std::string>)];

我不知道如何解决这个问题。有人可以提供一些帮助吗?谢谢。

【问题讨论】:

【参考方案1】:

lockfree::queue&lt;T&gt; 要求 T 有一个简单的析构函数(除其他要求外,请参阅 here)

std::string 不是trivial。因此queue&lt;std::string&gt; 格式不正确,您的reinterpret_cast 技巧将无济于事。

【讨论】:

谢谢。但是如何将字符串推入队列?似乎只有基本类型,例如 Integer 是微不足道的。 您可以推送动态分配的char* 并手动处理释放内存。或者使用常规的阻塞队列(例如来自 boost.thread 的 sync_queue) 非常感谢。动态 alllcated char* 工作正常。

以上是关于使用 sizeof(boost::lockfree::queue<std::string>) 时出错的主要内容,如果未能解决你的问题,请参考以下文章

boost::lockfree::spsc_queue 忙等待策略。有阻塞弹出吗?

使用 Boost 的 lockfree spsc_queue 时如何编译?

Boost lockfree deque 生产者与消费者多对多线程应用

evpp性能测试: 对无锁队列boost::lockfree::queue和moodycamel::ConcurrentQueue做一个性能对比测试

evpp性能测试: 对无锁队列boost::lockfree::queue和moodycamel::ConcurrentQueue做一个性能对比测试

boost::lockfree::queue多线程读写实例