jeudi 19 mai 2022

should a function return the pointer of a newly created object, or a unique_ptr of that object?

I remember watching Herb Sutter on conference talks, some years ago, trying to make a guideline along these lines:

if a function creates a new object on the heap, then it should always return it as a unique_ptr.

The idea was that it was safer, and intention-revealing.

To my surprise, this guideline seems to be missing from the CPP core guidelines today.

  • Has there been an issue with this guideline? Has it been abandoned?

  • Should we write functions like:

MyObject *create(Params p) {
  return new MyObject(p);
}

or

unique_ptr<MyObject> create(Params p) {
  return make_unique<MyObject>(p);
}

Aucun commentaire:

Enregistrer un commentaire