引用代替 getter
Reference in place of getters?
in C++使用引用代替getter是一种不好的做法吗?
例如:
class X
{
int mP;
public:
const int& P;
X():P(mP){}
};
及以后
X xl;
int h = xl.P;
只需考虑重构以使访问线程安全,这种方式不会很好地工作,并且需要在客户端类/函数中进行大量更改。
如果您有类成员,这些成员保证在实例的生存期内不会更改,则只需提供const int P;
并在类的构造函数中正确初始化它。
如果该值在类范围内可见,请使用static const int P;
在任何其他情况下,使用公共获取器:
int P() const; // a return type of 'const int &' would be redundant
第一枪实施:
int X::P() const
{
return mP;
}
线程安全实现:
class X {
{
// ...
private:
// ...
mutable std::mutex internalDataGuard;
};
int X::P() const
{
std::lock(internalDataGuard);
return mP;
}
这些都不好:
class X { public: int x; };
class X {
private: int m_x;
public: const int& get() const { return m_x; }
public: void set(const int& other) { m_x = other; }
};
class X {
private: int m_x;
public: const int& x() const { return m_x; }
public: void x(const int& other) { m_x = other; }
};
class X {
private: int m_x;
public: const int& x() const { return m_x; }
public: int& x() { return m_x; }
};
选择一个,这是一个设计决策。
让"const int&x"发布私有成员将起作用:
class X {
private: int m_x;
public: const int& x;
public: X() : m_x(0), x(m_x) {}
// Take care for copy and assignment
};
成本是更大的内存占用。
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 对类成员而不是 getter 的 Const 引用
- 使用const_cast const-ref getter 实现引用获取器的陷阱
- 为什么将指针转换为引用在我的访问器 (getter) 中不起作用?
- 此getter是否返回由构造函数或对班内对象的引用给出的引用?C
- C++ 防止通过 getter 更改引用
- 引用代替 getter
- 我可以使用常量引用而不是 getter 函数吗?
- C++重载getter两次,一次返回指针,另一次返回常量引用,都失败了
- 使用getter函数传递引用参数时出现意外行为
- 通过引用返回或创建一个典型的setter/getter
- 代理对象/引用getter与setter
- getter方法中的Const引用
- C++getter临时与常量引用