venkysmarty
venkysmarty

Reputation: 11431

Handle class and pointers

I am reading about handle class idiom in C++ at following link. It is mentioned that

http://bytes.com/topic/c/insights/651599-handle-classes-smart-pointer

Handle classes usually contain a pointer to the object implementation. The Handle object is used rather than the implemented object. This leaves the implemented object free to change without affecting the Handle object. This is exactly what happens with pointers. The object changes but the address in the pointer does not.

My question is that what does author mean by "This is exactly what happens with pointers. The object changes but the address in the pointer does not.". Appreciate if explained with example.

Thanks for your time and help

Upvotes: 2

Views: 990

Answers (3)

Oleksiy
Oleksiy

Reputation: 39810

It's pretty straight forward, maybe the wording is confusing.

The object your pointer points to, can be changed by something else in the program. Its (object's) values can be changed in other places in code. The pointer, however, does not change where it's pointing. That is why

implemented object free to change without affecting the Handle object.

For example,

class Class {
    public: int data;
};

int main() {

    Class myClass;

    Class* myClassPointer = &myClass;

    Class* otherPointer = &myClass;
    otherPointer->data = 10;

    cout << myClassPointer->data << endl;  // value changed, pointer still works

    cin.get();
    return 0;

}

Upvotes: 3

Vaughn Cato
Vaughn Cato

Reputation: 64308

For example, in this code:

int a = 5;
int *ap1 = &a;
int *ap2 = ap1;

ap1 and ap2 are two separate objects which point to a common object. These pointer objects can be created and destroyed without changing the object that they point to.

Upvotes: 0

urzeit
urzeit

Reputation: 2909

I think the author refers to the fact, that a handle-object can be copied and copied and copied and changes in the original data content of the referred object are accessible through each of the copies - just as it can be done with pointers.

Upvotes: 0

Related Questions