0

I had a question. I am working with external library in C++. The factory returns the unique pointer of the object. E.g. there is shapefactory which gives different shape different with different arguments

static std::unique_ptr<Shape> CreateShape(const std::string & );

I wanted to understand two things.

  1. First why the factory returns static unique pointer ? What are the advantages and disadvantages of returning static V/s non static

  2. If I am designing factory, when to return unique pointer V/s shared pointer ?

1201ProgramAlarm
  • 30,320
  • 7
  • 40
  • 49
Dhruvin Naik
  • 79
  • 10
  • 3
    No the member function `CreateShape()` is a static member function. You can call it without having a object of whaever class type that has CreateShape() – drescherjm Oct 27 '18 at 02:35
  • 1
    The `static` has nothing to do with the `std::unique_ptr` return value of that function, so your premise of (1) is at-best misguided, but regardless, erroneous. We also have no idea whether `CreateShape` is a static class function or just a local file-level `static` function, but again, it doesn't really matter other than that it is obvious the function itself is *not* a regular member function of some class.. Regarding (2), there is no specific reason other than guaranteed singular ownership. Whomever has that pointer owns the object outright. – WhozCraig Oct 27 '18 at 03:37
  • I would say pretty much *always* return `std::unique_ptr` because that can be converted to a `std::shared_ptr` if needed. – Galik Oct 27 '18 at 03:52
  • @Galik there is still overhead and if you know that shared_ptr is necessary it would be better – Slava Oct 27 '18 at 03:53

0 Answers0