【问题标题】:boost::shared_ptr<const T> to boost::shared_ptr<T>boost::shared_ptr<const T> 到 boost::shared_ptr<T>
【发布时间】:2010-06-10 01:07:18
【问题描述】:

我想将 const-ness 从 boost::shared_ptr 中剔除,但我 boost::const_pointer_cast 不是答案。 boost::const_pointer_cast 想要 const boost::shared_ptr&lt;T&gt;,而不是 boost::shared_ptr&lt;const T&gt;。让我们放弃强制性的“你不应该那样做”。我知道...但我需要这样做...那么最好/最简单的方法是什么?

为了清楚起见:

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

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

我需要知道魔法咒语()

【问题讨论】:

    标签: c++ boost casting constants shared-ptr


    【解决方案1】:

    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:是的,const_pointer_cast,就像 C++ 中的const_cast 一样,可以添加或删除 const 和 volatile 限定符,因此如果不指定,则无法知道所需的目标限定符。我很高兴能提供帮助。
    【解决方案2】:

    请注意,如果共享的const T 突然改变...

    ,其他“股东”会非常惊讶

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-19
      • 2010-11-27
      • 2018-05-13
      • 2013-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多