Returning a Reference to a Stack Object

 <  Free Open Study  >  

 #include <iostream.h>  class Point {  int x, y;  char* color; public:  Point(int = 0, int = 0, char* = ''Red'');  ~Point();  Point (const Point&);  void print();  const Point& operator=(const Point&);  const Point& operator+(const Point&); }; void Point::print() {  cout << ''I live at ('';  cout <<x<<'', ''<<y<<'') and '';  cout << ''I'm'' << color <<''.\n"; } const Point& Point::operator=(const Point& rhs) {  x = rhs.x; y = rhs.y;  delete color;  color = new char[strlen(rhs.color)+1];  strcpy(color, rhs.color); } // This function returns a hidden pointer // (i.e., a reference) to a temporary Point // object that will be destroyed upon return // from the function. const Point& Point::operator+(const Point& rhs) {  Point temp;  temp.x = x + rhs.x; temp.y = y + rhs.y;  delete temp. color; // Not exactly a good color-mixing scheme!  temp.color = new char[strlen(color)+strlen(rhs.color)+1];  sprintf(temp.color, ''%s%s'', color, rhs.color);  return(temp); main()} {  Point p1(10, 10, ''Blue'');  Point p2(20, 60, ''Green''); // The copy constructor is receiving a destroyed // Point object as an argument since the operator+ // function returns a hidden pointer to the // automatic variable temp. This variable had its // destructor called upon exit from operator+.  Point p3 = p1 + p2;  p3.print(); } 

Another attempt at a solution to this problem is to make the temporary Point object of internal static storage class. An internal static object is not created and destroyed upon entrance /exit from the function; it simply goes in and out of scope. This code will work fine, provided the operator is never used in a nested function call. Of course, one can imagine all sorts of uses for nesting addition operators. The C++ statement x+y+z is one of the more mundane yet valid examples. Because each call to operator+ uses exactly the same temporary Point object, the nested calls will stomp the memory of each other.

 <  Free Open Study  >  


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

Similar book on Amazon

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