Who`s Afraid to Be Const Correct? Take Your Object`s Bits Literally
(Page 1 of 5 )
This is the second article in a tutorial series covering const correctness. In this article, Jun Nakamura discusses some problems concerned with bitwise copy construction and bitwise constness, how to make your interface conceptually const, and how to make changes to an object that are not visible to the user.
A Bitwise Problem
Using const to strengthen the contracts in your code (like applying it to member functions to guarantee that the function won’t change the internal state of an object) is a good thing. But C++ would not be C++ if things couldn’t be made confusing one way or the other. First consider the following class:
class MyClass {
public:
// ctor makes m_pLabel point to a copy of label MyClass(char const *label) {
m_pLabel=new char[MAX_LABEL_LEN];
SetLabel(label);
}
~MyClass() {
try { delete m_pLabel; }
catch (...) { }
}
char* GetLabel() const { return m_pLabel; }
void SetLabel(char const *label) {
assert(label);
assert(static_cast<int>(strlen(label)+1)
< MAX_LABEL_LEN);
(void)sprintf(m_pLabel, “%s”, label);
}
private:
static int const MAX_LABEL_LEN;
char *m_pLabel;
};
int const MyClass::MAX_LABEL_LEN = 1024;
This is not a piece of code I would recommend you ever use (or write for that matter!), but it will serve my purpose here. Did you spot at least one big problem this class has?
The problems I am looking for are concerned with bitwise copy construction and bitwise constness.
Next: Bitwise Copy Construction >>
More C++ Articles
More By J. Nakamura