jeudi 8 juin 2017

C++ when to return by value and when to return a unique pointer to an object

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));
}

Aucun commentaire:

Enregistrer un commentaire