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>
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.
jogojapan
source share