Preventing a const member function from changing a member array

前端 未结 3 508
时光取名叫无心
时光取名叫无心 2021-01-14 15:14

Apparently, a const member function is still allowed to change data that the class member are pointing to. Here\'s an example of what I mean:

class MyClass
{         


        
3条回答
  •  日久生厌
    2021-01-14 16:00

    The reason you should use std::vector is actually because you want to store a collection of ints, and not an int pointer, so why not use it?

    It would also solve your const'ness issue.

    Here's how it works: declaring a method const will make all class members const. In your case, that means that in the method scope, your member data will become a constant pointer to an int. That means you can change the int (also meaning array members) as long as data points to the same location. Using std::vector, data would become a const std::vector, on which you could only call const functions. So yes, you should use std::vector.

提交回复
热议问题