You return a heap-allocated object which means you transfer ownership. I would suggest you use std::unique_ptr
as the return type
std::unique_ptr<Y> func(param)
{
return std::unique_ptr<Y>(new Y(param));
}
Even better is to use std::make_unique (if it is already available, otherwise write your own) or - if you use shared_ptr - std::make_shared. It is better for exception safety and in case of shared_ptr more efficient.
std::unique_ptr<Y> func(param)
{
return make_unique<Y>(param);
}
std::shared_ptr<Y> func(param)
{
return std::shared_ptr<Y>(param);
}
And be aware that your func
copied the parameter. You may want to use forwarding to avoid this.
template<class T, class U>
std::unique_ptr<T> make_unique1(U&& u)
{
return std::unique_ptr<T>(new T(std::forward<U>(u)));
}
template<class T, class... U>
std::unique_ptr<T> make_unique(U&&... u)
{
return std::unique_ptr<T>(new T(std::forward<U>(u)...));
}
std::shared_ptr
. Usestd::make_shared
.share_ptr
toshared_ptr
, it should work.std::shared_ptr
andstd::unique_ptr
as pointers, instead most of the time you should look at them from an ownership perspective.std::shared_ptr<Y> func(param)
isn't even valid C++. But props for at least considering smart pointers. its more than many would do.