【发布时间】:2021-08-05 21:40:16
【问题描述】:
我正在尝试将裸指针转换为智能指针。 但我不太确定如何在使用唯一指针时保留 currentBar(也将位于 myBars 中)
Class Foo
{
public:
Bar* getCurrentBar();
//!! other stuff not important
private:
Bar* currentBar;
std::vector<Bar *> myBars;
};
我不认为我应该使用共享指针,因为唯一拥有对象所有权的是 Foo,
到
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;
};
上述方法不起作用,但我想做与上述类似的事情。我该怎么做呢? (我宁愿不使用共享指针)。
【问题讨论】:
-
如果
Foo应该拥有指针,即使在有人调用getCurrentBar()之后,也不要返回unique_ptr。实现它:Bar* getCurrentBar() { return currentBar.get(); }.- 此外,您不能在unique_ptr和currentBar和myBars中包含相同的指针。顺便说一句,您是否必须使用指针?为什么不std::vector<Bar> myBars;? -
不是问题的主题,但是一旦您从公共 getter 返回指向非常量或非常量引用的指针,您就不需要将成员设为私有。通过调用
getCurrentBar,调用者可以直接访问该成员,绕过所有访问保护
标签: c++ smart-pointers unique-ptr