Who`s Afraid to Be Const Correct? Take Your Object`s Bits Literally - Bitwise Copy Construction
(Page 2 of 5 )
The bitwise copy construction problem falls outside the const topic, but since it is conceptually related to bitwise constness, I don’t want to keep it from you. Whenever you write or see a class that has a pointer as a data member, I want you to think of these (possible) bitwise problems and check that they have been solved for that particular class.
Take a look at the following test code:
MyClass *label1=new MyClass(“value1”);
(void)printf(“Label1: %sn”, label1->GetLabel());
MyClass *label2=new MyClass(“value2”);
(void)printf(“Label2: %sn”, label2->GetLabel());
label2=label1;
(void)printf(“Label1: %sn”, label1->GetLabel());
(void)printf(“Label2: %sn”, label2->GetLabel());
When you compile and run this code you will get the output you are expecting:
Label1: value1
Label2: value2
Label1: value1
Label2: value1
Did you think twice, however, when you saw the statement ‘label2=label1;’? Who created the assignment operator? (And yes, there is also a copy constructor available –- where did that come from?)
The C++ compiler will supply you with a copy constructor and an assignment operator, unless you specify them yourself. The copy construction and assignment are done in a bitwise manner, meaning that they will copy the value of the data members from the original class to the data members of the other class bit by bit.
For MyClass this means that *m_pLabel will be copied bit by bit from ‘label1’ to ‘label2’: so afterwards label1.m_pLabel and label2.m_pLabel are both pointing to the same memory location!
To prove my point:
label2->SetLabel(“value2”);
(void)printf(“Label1: %sn”, label1->GetLabel());
(void)printf(“Label2: %sn”, label2->GetLabel());
This will provide us with the following output:
Label1: value2
Label2: value2
The most obvious solution in this case would be to implement our own copy constructor and assignment operator. In one of my previous articles about pointers, I demonstrated how you can prevent your class from being copyable by declaring the copy constructor and assignment operator private.
The interface for MyClass would look like this:
class MyClass {
public:
MyClass(char const *label);
~MyClass();
char* GetLabel() const;
void SetLabel(char const *label);
private:
MyClass(MyClass const&);
MyClass& operator=(MyClass const&);
private:
static int const MAX_LABEL_LEN;
char *m_pLabel;
};
Next: Bitwise Constness >>
More C++ Articles
More By J. Nakamura