Leak 5

 <  Free Open Study  >  

Leak #5

Missing copy constructors. If the user of a C++ class attempts to invoke a constructor function that the implementor of that class has not defined, then the user expects to get an error from the compiler or, at a minimum, the linker. This is normally the case in C++, unless that constructor happens to be the copy constructor (also called the initialization constructor). The copy constructor is a constructor function whose sole argument is a reference to an object of the constructor's class. For example, the prototype of the copy constructor for the Point class looks like Point (const Point&); . If this constructor is not defined, then the compiler assumes its definition to be a memberwise copy of the data members (bitwise copy in C++ version 1.2). Unfortunately, memberwise (or bitwise) copying of a pointer is defined as copying the address from one location to another. The ramifications of this implicit pointer copying is that two objects will have pointers to the same dynamically allocated memory. When the first object is destroyed, its destructor will clean up the dynamically allocated memory associated with it. When the second object is destroyed , its destructor attempts to clean up the same memory. Deleting the same memory twice is considered an error and will probably corrupt the heap. A developer may argue that, by convention, no user of his or her class will call the copy constructor. Aside from the usual folly of programming by convention, there are issues dictating that a copy constructor be explicitly defined. Most calls to the copy constructor are not explicit calls. The copy constructor is called whenever one object is initialized to another of the same type, an object is passed by value as an argument to a function, or an object is returned by value from a function. This implicit behavior will cause memory leakage in variable- sized classes.

 <  Free Open Study  >  


Object-Oriented Design Heuristics
Object-Oriented Design Heuristics (paperback)
ISBN: 0321774965
EAN: 2147483647
Year: 1996
Pages: 180

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net