4

如何将 std::auto_ptr 更改为 boost::shared_ptr?以下是我的限制: 1. 我正在使用 API 类,我们将其称为 only_auto 以返回这些指针 2. 我需要在 auto_only 中使用调用 3. 我的语义涉及共享,因此我确实需要使用 shared_ptr) 4. 在class only_auto operator = 是私有的以防止应对 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();
    }
4

3 回答 3

4

构造shared_ptr函数声明为:

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

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

因为它需要一个非 const 左值引用,所以您不能使用右值调用此成员函数,这是您尝试做的事情:

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);
于 2012-05-24T16:28:07.030 回答
1

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

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

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

于 2012-05-24T18:25:44.407 回答
0

我认为

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

应该做的伎俩

于 2015-03-10T02:24:16.043 回答