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

Time:05-20

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

CodePudding user response:

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

This guideline is provided by the C Core Guidelines. This guideline is related to factory functions, which are functions whose primary purpose is to construct and initialize a new object.

See C.50: Use a factory function if you need “virtual behavior” during initialization which states :

Note The return type of the factory should normally be unique_ptr by default [...]

CodePudding user response:

It is covered in the C Core guidelines under I11:

https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#i11-never-transfer-ownership-by-a-raw-pointer-t-or-reference-t

What you should be doing is:

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

Only when you absolutely need reference mechanics, i.e. when constructing a polymorphic object and returning a base class, should you do this:

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