![]() |
![]() |
![]() |
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |
![]() |
![]() |
[an error occurred while processing this directive]
Notable items in this file are the calls to reference() and dereference() in the assignment operator and copy constructor. The object references the other object while it is working on it to prevent a dereference() call in another thread from destroying the object while the copying is in progress. There is one problem with this code. Can you spot it? (Feel free to skip the rest of this paragraph until you have played with the code.) The process of copying can destroy an object with no other references. Because a newly created object has a reference count of 0, referencing and then dereferencing the object in any way will cause the object to self-destruct. To fix it, make the copy constructor or assignment operator grab the mutex that protects the reference count variable, increment copyfrom. Refs, and free the mutex. Decrement the Refs variable at the end of the function, remembering the mutexes. This has the effect of bypassing the self-destruct code in the dereference() function. How It Works The trick with the classes as they are presented is to determine when to count references. The easiest way to accomplish this is to make a pointer class to encapsulate pointer functionality. The pointer objects can be created and fall out of scope ad nauseum, and the data will be valid until the last pointer object is deleted. At that point, the container object will self-destruct. The classes effectively deal with a number of problem areas:
Comments It is possible to accidentally grab a pointer to the data contained thats not accounted for through the overloaded operators of the ObjectPtr class. This is difficult to prevent. Having said this, it is not likely to happen if the programmer using the class understands the implications of the code. After all, it is possible to access private data members of classes from outside a class, too (by typecasting the object to an array of char, and then reading it as an array). Also, the data object being encapsulated within the ObjectContainer might need mutex protection for the data it contains. Because this is a data issue, I recommend that the data class handle this and not the container class.
|
![]() |
Products | Contact Us | About Us | Privacy | Ad Info | Home
Use of this site is subject to certain Terms & Conditions, Copyright © 1996-1999 EarthWeb Inc. All rights reserved. Reproduction whole or in part in any form or medium without express written permision of EarthWeb is prohibited.
|