I am using a function from an external library (here represented by the printer
-function).
By chance, I noticed, that I can pass a class member from a const
member function like done by the print()
-function. Even if I compile using
g++ -Wall -Wextra -Wpedantic -Werror -o test test.cpp
I don't obtain an error.
This seems to be horribly wrong, because effectively I am modifying the object by calling a const
member function. Why is the compiler not complaining?
Here is the code:
#include <iostream>
using namespace std;
void printer(void* data) {
static_cast<char*>(data)[0] = '1';
cout << static_cast<char*>(data) << endl;
}
void setUp(char* data, int length) {
for(int i=0; i<length; i++)
data[i] = '0';
data[length] = '\0';
}
class Test {
private:
char* data;
public:
Test(int length) {
data = new char(length+1);
setUp(this->data, length);
}
~Test() {
delete data;
}
void print() const {
printer(this->data);
}
};
int main() {
Test T(3);
T.print();
return 0;
}
My best guess is, that the compiler only guarantees, that the pointer variable is not modified, i.e. not pointing to a different physical address after the function call. But I also noticed, that the compiler throws errors when I try something similar with a std::vector<char>
instead of char*
and a modified print
-function:
void print() const {
printer(this->myVector.data());
}
So if my guess is correct, why is it not possible to do something similar with the pointer obtained by data()
of a STL vector?