c++ - 将 auto_ptr 转换为 shared_ptr

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

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

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

一个 super 简化的代码示例:

    #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();
    }

最佳答案

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);

关于c++ - 将 auto_ptr 转换为 shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10741422/

相关文章:

c++ - VS2017 'M_PI' : undeclared identifier

C++隐式转换规则

c++ - 通过继承扩展 shared_ptr

c++ - 赋予容器其子代的所有权,但让子代使用智能指针存储对其父代的引用

c++ - 了解 C++ std::shared_ptr

C++从字符串指针解析int

c++ - 强制将文件写入磁盘

c++ - boost::sp_convertible 的解释

c++ - x86/C++ - 指向指针 : Const being violated by compiler? 的指针

C++03 带 free() 的智能指针