How to convert an instance of an object to an instance of shared_ptr

Suppose I had two types of shared_ptr, for example

boost::shared_ptr<ObjA> sptrA; boost::shared_ptr<ObjB> sptrB; 

Now suppose sptrA->SomeMethod() returns a simple ObjB type (and not a generic ptr). Is it possible to save this type in sptrB? So that I can do something like this so that the return type instance is automatically converted to boost_shared ptr

 sptrB = sptrA->SomeMethod(); 

I asked this question only curiosity and is it possible or not?

+7
source share
2 answers

The most standard way to create boost:shared_ptr objects is to use the make_shared function provided by Boost:

 #include <boost/shared_ptr.hpp> #include <boost/make_shared.hpp> struct A {}; A generator() { return A(); } int main() { using namespace boost; shared_ptr<A> p = make_shared<A>(generator()); return 0; } 

Since the generator() function returns object A by value, the syntax above implies that new is called with copy constructor A , and the resulting pointer is wrapped in an object with a common pointer. In other words, make_shared does not convert to a generic pointer; instead, it creates a copy of the object on the heap and provides memory management for this. This may or may not be what you need.


Note that this is equivalent to std::make_shared for std::shared_ptr in C ++ 11.


One way to provide a convenient syntax that you mentioned in your question is to define a conversion operator for shared_ptr<A> for A :

 struct A { operator boost::shared_ptr<A>() { return boost::make_shared<A>(*this); } }; 

Then you can use it as follows:

 shared_ptr<A> p = generate(); 

This will automatically convert the object returned by the function. Again, conversion here really means allocating a heap, copying and wrapping in a common pointer. So I'm not sure if I recommend defining such a convenience conversion operator. This makes the syntax very convenient, but it, like all implicit conversion operators, can also mean that you implicitly invoke these "conversions" in places you did not expect.

+5
source

It depends on whether ObjA::SomeMethod a copy, link, or pointer. In the first two cases, it would be impossible to wrap it in shared_ptr (because shared_ptr needs a pointer).

A third case is possible, but you must be careful. Make sure that after binding the pointer to the object in shared_ptr no one else tries to control the lifetime of this object.

For example, if you return a raw pointer, wrap it in a shared pointer, and then, at some point later in the program, someone delete the same pointer, you will have a problem.

+1
source

All Articles