我有一段C++ Qt
代码,它接收网络消息并将其解码为由智能指针管理的Google protobuf。该函数对protobuf进行一些最小的结构解析,以查看是否存在可选消息字段,如果存在某些消息,则分派(dispatch)信号。
当前,这些信号包含智能指针的拷贝,该指针包含了整个消息,并利用了引用计数。但是,我想将智能指针分派(dispatch)到消息的特定部分,以便下游处理程序不需要重新解析整个protobuf。我不能简单地创建一个指向相关消息部分的新智能指针,因为当新指针超出范围时,它将尝试释放该部分。
试图说明这一点,但省略了一些安全检查:
void Interface::processProtobuf(QByteArray const & networkData) {
QSharedPointer<proto_message> msg(new proto_message);
msg->ParseFromArray(networkData.data(), networkData.length());
if (msg->has_configuration()) {
// This will eventually attempt to free, thus causing corruption
// of msg.
QSharedPointer<config_message> cfg(msg->mutable_configuration());
emit configurationChanged(cfg);
// I resorted to this, which forces the receiver to re-parse
// the data structure (which might be expensive for a deeply-nested
// message) to get the desired 'configuration' pointer.
emit configurationChanged(msg);
}
}
这样做,我确实需要一种方法来创建一个“相关的”子指针,该子指针继承(并递增)父指针上的引用计数,以便直到所有的子元素和父元素都用完后才调用数据析构函数。范围。在标准的智能指针实现之一中是否提供了此功能,或者我是否创建了不必要的特殊情况?我找到的最接近的东西是
Qt
的QSharedDataPointer<>
,但是我认为在创建子指针的情况下它没有帮助。不需要
Qt
解决方案。这更多是一个学术问题,因为我的解决方法适合我目前的情况。 最佳答案
std::shared_ptr
(如果没有C++ 11,则为boost::shared_ptr
)具有一个构造函数,该构造函数使用共享的指针r
和指针p
。构造的共享指针将指向*p
,但与r
共享所有权。这应该是您所需要的。
构造函数的签名是
template<class Y> shared_ptr(const shared_ptr<Y>& r, T *p) noexcept;