在C++中使用const成员变量有什么优点

2024-03-22

我写代码像

template <typename XAxis, typename YAxis>
class Interpolation {
public:
    using x_value_type = typename XAxis::value_type;
    using y_value_type = typename YAxis::value_type;

    Interpolation(const XAxis& x_axis, const YAxis& y_axis)
        : _x_axis(x_axis), _y_axis(_y_axis)
    {}

public:
    y_value_type interpolate(const x_value_type& x) const;

private:
    const XAxis _x_axis;
    const XAxis _y_axis;
};

当我想要成员变量是不可变的时。

我感到有点焦虑,为什么我认为我可能因某种原因知道上面的代码是非法的或坏的代码。
您认为常量成员变量有什么好处或没有什么好处?
请告诉我你的理由。


实际优势const成员的缺点是,除非它们属于具有用户定义的默认构造函数的类,否则必须显式初始化它们。因此,符合标准的编译器将捕获任何丢失的初始化。这也是一个优点const成员表达了预期的功能,即在对象的生命周期内不发生任何变化,因此有助于编译器检测任何可能(错误地)更改值的代码。

另一方面,更重要的是,使用默认功能,它们会阻止副本分配和移动。

这些注意事项也适用于引用数据成员,可以将其(概念上)视为自动取消引用const指针成员。


对于客户端代码,但不是类自己的代码,逻辑const-ness,不变性,可以用 non- 来表达public non-const数据成员与const访问器成员函数。


¹ Unfortunately Visual C++ 2015 accepts at least some cases of uninitialized const member that doesn't have a user-defined default constructor, so as of this writing one can't be 100% sure that the compiler will catch missing initializations.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在C++中使用const成员变量有什么优点 的相关文章

随机推荐