Search code examples
c++smart-pointersunique-ptr

Best Practices? Converting from pointers to Unique_Ptrs


I am trying to convert from naked pointers to smart pointers. But I am not quite sure how to keep currentBar (Who will also be located in myBars) while using unique pointers

Class Foo
{
  public:
     Bar* getCurrentBar();
     //!! other stuff not important
  private:
     Bar* currentBar;
     std::vector<Bar *> myBars;
  
};

I don't believe I should use a shared-pointer as the only thing which has ownership of the object is Foo,

to

Class Foo
{
   public:
      std::unique_ptr<Bar> getCurrentBar(); //? returns currentBar, whatever currentBar is;
   private:
      std::unique_ptr<Bar> currentBar; //? What do I do here?
      std::vector<std::unique_ptr<Bar>> myBars;
 };

The above doesn't work, but I would like to do something similar to the above. How do I do this? (I would prefer not to use a shared pointer).


Solution

  • There is nothing wrong with non-owning raw pointers. Use the unique_ptr in the vector to manage the lifetimes, and then use regular pointers or references for your interface. That would look like

    Class Foo
    {
      public:
         Bar* getCurrentBar(); 
         // or Bar& getCurrentBar();
      private:
         Bar* currentBar;
         std::vector<std::unique_ptr<Bar>> myBars;
      
    };