Convert auto_ptr to shared_ptr

How can I change std :: auto_ptr to boost :: shared_ptr? Here are my limitations: 1. I use the API class, allow it only_auto, which returns these pointers 2. I need to use the call in auto_only 3. My semantics include sharing, so I need to use shared_ptr) 4. In the only_auto class operator = is private to prevent a match 5. Also, only_auto should be made by cloning a call to std :: auto_ptr creat_only_auto ();

I know that the template is explicitly shared_ptr (std :: auto_ptr and r); but how to use it in this scenario?

Simplified code example:

#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
source share
3 answers

The shared_ptr constructor is declared as:

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

Note that it requires a reference to the lvalue constant. It does this so that it can correctly release the auto_ptr property for the object.

Since it accepts a reference to a non-constant lvalue, you cannot call this member function with rvalue, which is what you are trying to do:

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

You need to save the result of only_auto::create_only_auto() in a variable, and then pass this variable to the shared_ptr constructor:

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

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

Most valid uses of auto_ptr are source, compatible with std :: unique_ptr, so you may need to convert to this. If all goes well, then you are safe. (You might want to switch to using typedef if you have not already done so, so you can easily change the type in the future.) If you have a compilation error, you may have an error in your code where you previously used the invalid auto_ptr.

I think you should only look at moving to std :: shared_ptr after you have checked things with unique_ptr, and you see that you really need joint ownership (often you can just use unique ownership indicators without ownership).

+1
source

I think,

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

gotta do the trick

0
source

Source: https://habr.com/ru/post/1414192/


All Articles