I am getting compilation error with g++4.6 and boost 1.42 when using boost::make_shared<T>(...)
, whereas shared_ptr<T>(new T(...))
compiles just fine. I am unfortunately not able to isolate a minimal example (anything I tried compiled just fine for both), but perhaps someone could explain to me the difference.
I am instatiating an instance of shared_ptr<ResidualsFunctor> f
, where ResidualsFunctor
has the following ctor:
ResidualsFunctor(int,int,StaticEquilibriumSolver*)
This
f=shared_ptr<ResidualsFunctor>(new ResidualsFunctor(0,0,this)); // this is a StaticEquilibriumSolver*
compiles just fine, whereas
f=make_shared<ResidualsFunctor>(0,0,this);
tells me:
/usr/include/boost/smart_ptr/make_shared.hpp: In function 'boost::shared_ptr<T> boost::make_shared(Args&& ...) [with T = StaticEquilibriumSolver::ResidualsFunctor, Args = int, int, StaticEquilibriumSolver* const]':
pkg/sparc/SparcField.cpp:472:49: instantiated from here
/usr/include/boost/smart_ptr/make_shared.hpp:148:5: error: no matching function for call to 'forward(int&)'
/usr/include/boost/smart_ptr/make_shared.hpp:148:5: note: candidate is:
/usr/include/boost/smart_ptr/make_shared.hpp:90:40: note: template<class T> T&& boost::detail::forward(T&&)
Is it a bug in boost? In gcc? My fault which I don't see?
So, if you throw exception from your class' constructor, then std::make_shared will throw it too. Besides exceptions thrown from constructor, std::make_shared could throw std::bad_alloc exception on its own. Therefore, you don't need to check if the result of std::make_shared is nullptr .
It constructs an object of type T passing args to its constructor, and returns an object of type shared_ptr that owns and stores a pointer to it.
The header file <boost/make_shared. hpp> provides a family of overloaded function templates, make_shared and allocate_shared , to address this need. make_shared uses the global operator new to allocate memory, whereas allocate_shared uses an user-supplied allocator, allowing finer control.
The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.
boost::make_shared
allocates an object of the given type, using the given parameters and wraps it in a boost::shared_ptr
. Therefore, it has to forward the arguments you give it to a constructor. In order for your call to it to work, it must be able to find a constructor that matches the argument list you give it.
Your problem seems to be that it is having difficulty forwarding your integer arguments. I'm not sure how, as all of your arguments are basic types.
Boost 1.42 was released 18 months ago; GCC 4.6 was released rather more recently than that. I'd guess that if you update to a more recent version of Boost, you wouldn't have this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With