Reputation: 4784
I have boost shared_ptr
as a parameter to function, i would like this parameter to have some default value.
void foo(boost::shared_ptr<myclass> ptr = nullptr);
because ptr is not a pointer, but a class..
so what can i do ?
i found a similar question : boost::shared_ptr and nullptr in default template function argument
But the solution there is just to switch to std::shared_ptr
, but i can't do it
Thanks
Upvotes: 0
Views: 4087
Reputation: 15075
It's perfectly ok to initialize boost::shared_ptr
with nullptr
. It has a special constructor for this:
#if !defined( BOOST_NO_CXX11_NULLPTR )
shared_ptr( boost::detail::sp_nullptr_t ) BOOST_NOEXCEPT : px( 0 ), pn() // never throws
{
}
#endif
(boost::detail::sp_nullptr_t
resolves to nullptr_t
in a portable manner)
Upvotes: 2
Reputation: 171283
Since you're using nullptr
you must be using C++11, so you should be able to do this:
void foo(boost::shared_ptr<myclass> ptr = {});
That makes the default argument a default-constructed shared_ptr
, which is the same as one initialized with nullptr
. It requires your compiler to support uniform initialization syntax, instead of requiring your Boost version to support constructing shared_ptr
from nullptr_t
.
If your compiler can't handle that then use ForEveR's answer.
Upvotes: 2
Reputation: 17163
I think the problem is not "being class" but that the involved constructor is explicit. And your form would require implicit conversion. You can work it around using an explicit form: boost::shared_ptr<myclass>(nullptr)
or boost::shared_ptr<myclass>()
, whichever is supported for your version.
Upvotes: 1
Reputation: 55887
Why not simply?
void foo(boost::shared_ptr<myclass> ptr = boost::shared_ptr<myclass>());
Upvotes: 1