1
votes

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).

1
If Foo is supposed to own the pointer even after someone has called getCurrentBar(), don't return a unique_ptr. Make it: Bar* getCurrentBar() { return currentBar.get(); }.- Also, you can't have the same pointer wrapped in unique_ptr in both currentBar and myBars. Btw, do you have to use pointers at all? Why not std::vector<Bar> myBars;?Ted Lyngmo
not the topic of the question, but once you returned a pointer to non-const or a non-const reference from a public getter you don't need to make the member private. By calling getCurrentBar the caller has direct access to the member, all access protection is bypassed463035818_is_not_a_number

1 Answers

3
votes

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