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).
Foo
is supposed to own the pointer even after someone has calledgetCurrentBar()
, don't return aunique_ptr
. Make it:Bar* getCurrentBar() { return currentBar.get(); }
.- Also, you can't have the same pointer wrapped inunique_ptr
in bothcurrentBar
andmyBars
. Btw, do you have to use pointers at all? Why notstd::vector<Bar> myBars;
? – Ted LyngmogetCurrentBar
the caller has direct access to the member, all access protection is bypassed – 463035818_is_not_a_number