What I'm wondering is, how does returning by value a Cat
actually differ from returning an std::unique_ptr<Cat>
in terms of passing them around, memory management and using them in practice.
Memory management wise, aren't they the same? As both a returned by value object and an object wrapped in a unique_ptr will have their destructors triggered once they go out of scope?
So, how would you compare both pieces of code:
Cat catFactory(string catName) {
return Cat(catName);
}
std::unique_ptr<Cat> catFactory(string catName) {
return std::unique_ptr(new Cat(catName));
}
Cat
can be move-constructed the is no reason to make a pointer. Also,unique_ptr
cannot be copied. – Designerunique_ptr
values can be released from the pointer and used as a dynamically allocated object. Value is generally they way to go as @HenriMenke pointed out, however using aunique_ptr
allows you to extract the object for use beyond the scope of the ptr. – Wexler