【问题标题】:converting a auto_ptr to a shared_ptr将 auto_ptr 转换为 shared_ptr
【发布时间】:2012-05-24 16:20:13
【问题描述】:

如何将 std::auto_ptr 更改为 boost::shared_ptr?这是我的限制: 1. 我正在使用一个 API 类,我们称之为 only_auto 来返回这些指针 2.我需要使用auto_only中的调用 3. 我的语义涉及共享,所以我确实需要使用 shared_ptr) 4. 类中 only_auto 运算符 = 是私有的以防止应对 5. only_auto 对象也必须通过克隆调用 std::auto_ptr creat_only_auto();

我知道模板显式 shared_ptr(std::auto_ptr & r);但是在这种情况下我该如何使用它呢?

一个超级简化的代码示例:

    #include <iostream>
    #include <memory>
    #include <boost/shared_ptr.hpp>

    using namespace std;

    class only_auto
    {
      public:
      static auto_ptr<only_auto> create_only_auto();
      void func1();
      void func2();
      //and lots more functionality

      private:
      only_auto& operator = (const only_auto& src);
    };

    class sharing_is_good : public only_auto
    {
      static boost::shared_ptr<only_auto> create_only_auto()
      {
        return boost::shared_ptr (only_auto::create_only_auto()); //not the correct call but ...
      }

    };

    int main ()
    {
       sharing_is_good x;

       x.func1();
    }

【问题讨论】:

    标签: c++ shared-ptr smart-pointers auto-ptr


    【解决方案1】:

    shared_ptr 构造函数声明为:

    template<class Other>
    shared_ptr(auto_ptr<Other>& ap);
    

    请注意,它采用非常量左值引用。这样做是为了正确释放auto_ptr 对对象的所有权。

    因为它需要一个非常量的左值引用,所以你不能用右值调用这个成员函数,这是你想要做的:

    return boost::shared_ptr(only_auto::create_only_auto());
    

    您需要将only_auto::create_only_auto() 的结果存储在一个变量中,然后将该变量传递给shared_ptr 构造函数:

    std::auto_ptr<only_auto> p(only_auto::create_only_auto());
    return boost::shared_ptr<only_auto>(p);
    

    【讨论】:

    • 我认为这个解决方案过于复杂
    【解决方案2】:

    3. My semantics involves sharing so I do need to use a shared_ptr)

    auto_ptr 的大多数有效用法都与 std::unique_ptr 源兼容,因此您可能需要考虑转换为它。如果一切正常,那么你就是安全的。 (如果您还没有使用 typedef,您可能希望改用 typedef,这样您以后可以轻松更改类型。)如果您遇到编译错误,您的代码中可能存在错误,您之前使用的是无效的auto_ptr.

    我认为您应该只在使用 unique_ptr 验证事物并且发现您确实需要共享所有权(通常您可以只使用唯一所有权和非所有权指针)之后才考虑迁移到 std::shared_ptr。

    【讨论】:

      【解决方案3】:

      我认为

      return boost::shared_ptr<only_auto>(only_auto::create_only_auto().release());
      

      应该做的伎俩

      【讨论】:

        猜你喜欢
        • 2023-03-06
        • 1970-01-01
        • 2012-07-22
        • 2017-08-06
        • 2010-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多