boost::shared_ptr<const T> 转换为 boost::shared_ptr<T>

4
我想将一个boost::shared_ptr中的const属性去掉,但是boost::const_pointer_cast不是答案。 boost::const_pointer_cast需要一个const boost::shared_ptr<T>,而不是boost::shared_ptr<const T>。 让我们放弃“你不应该这样做”的义务。 我知道...但我需要这样做...那么最好/最简单的方法是什么?

为了清晰起见:

boost::shared_ptr<const T> orig_ptr( new T() );

boost::shared_ptr<T> new_ptr = magic_incantation(orig_ptr);

我需要知道magic_incantation()的魔法咒语。

2个回答

9

boost::const_pointer_cast 是您想要使用的函数:

boost::shared_ptr<const int> ci(new int(42));
boost::shared_ptr<int> i(boost::const_pointer_cast<int>(ci));

这对你不起作用吗?我使用了Boost 1.43和Visual C++2010 C++0x实现进行了测试,两者都没有问题。


实际上……当我指定了模板参数时,它对我起作用了。由于第一次没有使用它,然后被编译器的错误信息所迷惑。谢谢。 - Flevine
@Flevine:是的,const_pointer_cast和C++中的const_cast一样,可以添加或删除const和volatile限定符,因此如果没有指定目标限定符,则无法知道所需的目标限定符。我很高兴能够帮助到您。 - James McNellis

2
请注意,其他“股东”将至少非常惊讶,如果共享的const T突然发生变化...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接