在C ++中使用const成员变量是否有优势 [英] Are there advantages of using const member variable in C++

查看:72
本文介绍了在C ++中使用const成员变量是否有优势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写类似的代码

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;
};

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

when i want to intent that member variables is immutable.

我有点担心为什么我出于某种原因认为上面的代码是非法的或错误的代码.
您如何看待常量成员变量是否有益?
请告诉我您的原因.

I feel a little anxious why I think that I might be known above code is illegal or bad code by some reason.
How do you think that constant member variables are beneficial or not?
Please tell me with your reason.

推荐答案

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

A practical advantage of const members is that unless they're of a class with user defined default constructor, they have to be explicitly initialized. So a ¹standard-conforming compiler will catch any missing initialization. It's also an advantage that const members express the intended functionality, namely no change over the lifetime of an object, and so help the compiler to detect any code that otherwise would (erroneously) change the values.

另一方面,更重要的是,它们具有默认功能,可防止副本分配和移动.

On the other hand, which can more important, with the default functionality they prevent copy assignment and moving.

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

These considerations also apply to reference data members, which can be regarded (conceptually) as auto-dereferenced const pointer members.

对于客户端代码,而不是类自己的代码,可以通过使用具有const访问器成员函数的非publicconst数据成员来表示逻辑const-不变性

For client code, but not the class' own code, the logical const-ness, the immutability, can be expressed by using non-public non-const data members with const accessor member functions.

¹不幸的是,Visual C ++ 2015至少接受了一些未初始化的const成员的情况,这些成员没有用户定义的默认构造函数,因此在撰写本文时,不能100%确定编译器将捕获缺少的初始化.

¹ 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.

这篇关于在C ++中使用const成员变量是否有优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆