简体   繁体   English

常量用法-要解决此问题,应在此处进行哪些更改?

[英]Const usage - What should be changed here to fix the issue?

I was reading Effective C++ book and it was talking about const correctness. 我在读《有效的C ++》,谈论的是const正确性。 The following code block was given: 给出了以下代码块:

class CTextBlock {
public:
    ...
    char& operator[](std::size_t position) const // inappropriate (but bitwise
    { return pText[position]; }                  // const) declaration of
                                                 // operator[]
private:
    char *pText;
};

The book was describing the potential issue with the above usage. 这本书正在描述上述用法的潜在问题。

const CTextBlock cctb("Hello"); // declare constant object
char *pc = &cctb[0];            // call the const operator[] to get a
                                // pointer to cctb’s data
*pc = ’J’;                      // cctb now has the value “Jello”

What should be changed so that the assignment used in the last line is forbidden? 应该更改什么才能禁止最后一行中使用的分配? The book didn't give a solution to the problem. 这本书没有给出解决问题的办法。

Thank you in advance for your help! 预先感谢您的帮助!

This is a result of how the different parts of the code work. 这是代码的不同部分如何工作的结果。 Const is supposed to provide guidance on the usage of objects and prevent programming mistakes. const应该为对象的使用提供指导,并防止编程错误。 By using it you are telling other programmers that this value should not be changed. 通过使用它,您正在告诉其他程序员不应更改此值。 There isn't actually a way to ensure that the data isn't changed. 实际上,没有一种方法可以确保数据不会被更改。 this is because in c++ there are a number of ways of accessing the underlying memory and changing it. 这是因为在c ++中,有多种访问基础内存并对其进行更改的方法。 In the example you have given this is through the use of pointers. 在示例中,您通过使用指针给出了这一点。

Why is this you might ask. 您可能会问为什么。 A great answer can be found at: http://www.cprogramming.com/tutorial/const_correctness.html The relevant section reads as follows: 可以在以下位置找到一个很好的答案: http : //www.cprogramming.com/tutorial/const_correctness.html相关部分的内容如下:

First, why would you ever want to have the ability to change data in a class that's declared const? 首先,为什么要拥有在声明为const的类中更改数据的功能? This gets at the heart of what constness means, and there are two ways of thinking about it. 这是constness含义的核心,有两种思考方式。 One idea is that of "bitwise constness", which basically means that a const class should have exactly the same representation in memory at all times. 一个想法是“按位常量”,这基本上意味着const类在任何时候都应该在内存中具有完全相同的表示形式。 Unfortunately (or fortunately), this is not the paradigm used by the C++ standard; 不幸的是(或幸运的是),这不是C ++标准所使用的范例。 instead, C++ uses "conceptual constness". 相反,C ++使用“概念常数”。 Conceptual constness refers to the idea that the output of the const class should always be the same. 概念常量是指const类的输出应始终相同的想法。 This means that the underlying data might change as long as the fundamental behavior remains the same. 这意味着只要基本行为保持不变,基础数据就可能会更改。 (In essence, the "concept" is constant, but the representation may vary.) (本质上,“概念”是恒定的,但表示形式可能有所不同。)

There are other ways to ensure that particular values remain constant ect that are harder to change or cannot be changed at runtime it that is your goal. 还有其他方法可以确保特定值保持不变,这是您的目标,在运行时更难更改或无法更改。 You can also look at using #define or enum depending on what you are trying to achieve. 您还可以根据要实现的目标使用#define或enum。 I would recommend that before using any of them you research the differences as whilst they all perform similar functions the edge cases can have very different results and each on has different limitations. 我建议在使用它们之前,先研究一下差异,因为它们虽然都执行相似的功能,但边缘情况可能会有非常不同的结果,并且每种情况都有不同的局限性。 It is also worth noting that some developers have very strong opinions on which of these options should be used and when. 还值得注意的是,一些开发人员对应该使用这些选项中的哪个以及何时使用有非常强烈的意见。 For example is espoused that you should favour enum over #define for aa number of reasons as seen here: http://blogs.msdn.com/b/doronh/archive/2006/03/27/562502.aspx 例如,出于多种原因,您认为应该让枚举胜于#define,如下所示: http : //blogs.msdn.com/b/doronh/archive/2006/03/27/562502.aspx

A good description of the difference between enum and const can be found here: http://www.codeproject.com/Articles/4354/Enum-vs-Const 可以在以下位置找到对枚举和const之间差异的良好描述: http : //www.codeproject.com/Articles/4354/Enum-vs-Const

It is also worth noting that the way const works in c versus c++ is different so ensure when you are reading about how to use const and when that you are reading about its application in the correct language. 还值得注意的是,const在c和c ++中的工作方式是不同的,因此请确保当您正在阅读有关如何使用const以及何时以正确的语言阅读const的应用程序时。

访问器应返回const char &以限制对返回值的写访问。

const char& operator[](std::size_t position) const

would prevent that, except if the user of the code used const_cast to remove the const . 可以避免这种情况,除非代码的用户使用const_cast删除const

Adding const means that the data that the reference refers to can't be changed 添加const意味着引用所引用的数据无法更改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM