假设您正在定义两个类,A 和 B,B 有一个指向 A 实例的指针,并负责管理该实例的生命周期。像这样:
class A;
class B
{
public:
B(A *a);
~B() { delete m_a; }
private:
A *m_a;
};
B::get_a
方法返回常量引用是否更合适:
const A &get_a() const
{
return *m_a;
}
或者只返回指针:
const A *get_a() const
{
return m_a;
}
最佳答案
B has a pointer to an instance of A, and is responsible for managing the lifetime of that instance.
B
是唯一指针的实现吗?标准提供了唯一指针的实现:std::unique_ptr
。我建议使用它代替 B
。
Would it be more appropriate for the method B::get_a to return a constant reference:
取决于 m_a == nullptr
是否是 B
的有效状态。如果是,那么如果您想返回引用,则需要抛出这种情况。
关于c++ - 通过引用返回拥有的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53086751/