【发布时间】:2016-09-26 11:50:11
【问题描述】:
我有一小段代码需要优化。线程“A”为堆对象创建了一个 boost shared_ptr。线程“A”将 shared_ptr 写入线程安全队列。线程“B”读取 shared_ptr,使用它,然后销毁它。
密集的分析/测试证明,将 shared_ptr 复制进/出队列并调整引用计数是昂贵的。因此,我想通过引用将共享 ptr 传递给队列。我还想使用 std::move 将 shared_ptr 移动到队列中,而不是构造一个新的 shared_ptr,(我知道这会使传递给队列的 shared_ptr 参数无效)。
在我加入一些多态性之前,所描述的一切都很好。我不能通过 ref 将 shared_ptr 传递给派生的 obj 到期望将 shared_ptr 传递给基类的函数。我把它归结为一个非常小的片段,它暴露了让我困惑的行为。
#include <boost/shared_ptr.hpp>
class Base
{
};
class Derived : public Base
{
};
int main()
{
boost::shared_ptr<Derived> pDerived(new Derived()); // simple creation
boost::shared_ptr<Derived> &alias1 = pDerived; // works fine
const boost::shared_ptr<Base> &alias2 = pDerived; // also works fine
boost::shared_ptr<Base> &alias3 = pDerived; // compilation error
//native pointers
Derived *alias4 = pDerived.get(); //works
const Base *alias5 = pDerived.get(); //works
Base *alias6 = pDerived.get(); //works
//native references
Derived &alias7 = *pDerived; // works
const Base &alias8 = *pDerived; // works
Base &alias9 = *pDerived; // works
}
我不明白为什么分配给 alias2 是完全正常的,但是分配给 alias3 会产生编译器错误。有人可以解释一下吗?我需要类似 alias3 示例的功能,但无法使其工作。
【问题讨论】:
-
std::shared_ptr<Base>& alias3 = static_cast<std::shared_ptr<Base>>( pDerived ); -
你也可以尝试使用 boosts
static_cast:alias3 = boost::static_pointer_cast<Base>(pDerived); -
就像 Eissa N. 建议的那样,强制转换会导致编译错误:
invalid initialization of non-const reference of type âboost::shared_ptr<Base>&â from an rvalue of type âboost::shared_ptr<Base>â boost::shared_ptr<Base> &alias3 = boost::static_pointer_cast<Base>(pDerived);即使这确实有效,临时 rval 对象的创建正是我出于效率原因试图避免的.
标签: c++ multithreading boost reference shared-ptr