Suppose I had two shared_ptr types such as
boost::shared_ptr<ObjA> sptrA;
boost::shared_ptr<ObjB> sptrB;
Now suppose that sptrA->SomeMethod() returned a simple ObjB type (not a shared ptr). Is it possible for me to store that type somehow in sptrB ? So that I could do something like this so that the returned type instance is automatically converted to boost_shared ptr
sptrB = sptrA->SomeMethod();
I asked this question just of curiosity and whether it is possible or not ?
The most standard way of creating
boost:shared_ptrobjects is to use themake_sharedfunction provided by Boost:Since the
generator()function returns anAobject by value, the syntax above implies thatnewis invoked with the copy contructor ofA, and the resulting pointer is wrapped in a shared-pointer object. In other words,make_shareddoesn’t quite perform a conversion to shared pointer; instead, it creates a copy of the object on the heap and provides memory management for that. This may or may not be what you need.Note that this is equivalent to what
std::make_shareddoes forstd::shared_ptrin C++11.One way to provide the convenient syntax you mentioned in your question is to define a conversion operator to
shared_ptr<A>forA:Then you can use it as follows:
This will automatically “convert” the object returned by the function. Again, conversion here really means heap allocation, copying and wrapping in a shared pointer. Therefore, I am not really sure if I’d recommend defining such a convenience conversion operator. It makes the syntax very convenient, but it, as all implicit conversion operators, may also mean that you implicitly cause these “conversions” to happen in places you didn’t expect.