Reputation: 111
I read a line in Meyers: "A member function that modifies what a pointer points to frequently doesn`t act const. But if only the pointer is in the object, the function is bitwise const, and compilers wont complain."
I fail to understand that modifying a pointer in a function cannot maintain its bitwise constantness since its a member variable...
Even if we assume that bitwise constantness is only for values that pointers point to and not for the pointer addresses themselves.. Then why does it matter if its the only member variable in the class or if its not the only only member variable..
Upvotes: 4
Views: 152
Reputation: 15916
Basically this means that if you had
struct Foo
{
int bar;
};
you couldn't have a const member function change the value of bar
.
However if bar
is a pointer to an int
, you could change the value of the int in a const method because the int
is not actually part of the struct.
Both versions achieve the same goal (i.e. change the value of the int
) but in the first version you are breaking bitwise constness and the compiler will complain, in the second it wont.
Upvotes: 4
Reputation: 9570
If I read it correctly, a member function usually isn't qualified const
if it modifies a value pointed at by a pointer stored in the current object:
class A {
char* string;
public:
void UpCaseString() { strupr(string); }
....
}
The UpCaseString()
method modifies data which 'belong' to the object, so it usually would not be declared as const. However it actually modifies some buffer allocated outside the current object, the instance of A
class has only a char*
pointer to the buffer—so the buffer can still be modified even when the object itself is const
:
class A {
char* string;
public:
void UpCaseString() const { strupr(string); }
....
}
void foo(A const &a) {
a.UpCaseString();
}
Member a.string
is not modified here.
Upvotes: 0
Reputation: 206577
Take the following simple classes:
class A
{
public:
A(int d = 0) : data(d) {}
void func() const
{
++data; // Can't do this. That's changing
// the bitwise content of this.
}
private:
int data;
};
And
class B
{
public:
A(int d = 0) : data(new int(d)) {}
void func() const
{
++(*data); // Can do this. That doesn't change
// the bitwise content of this.
}
private:
int* data;
};
Upvotes: 1
Reputation: 27567
It's bitwise const
because the member function only
modifies what [the] pointer points to
so the object instace data (the member pointer) doesn't change only the object on the heap that it points to.
Upvotes: 2