home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #19 / NN_1992_19.iso / spool / comp / std / cplus / 1121 < prev    next >
Encoding:
Text File  |  1992-09-01  |  2.0 KB  |  53 lines

  1. Newsgroups: comp.std.c++
  2. Path: sparky!uunet!cs.utexas.edu!torn!cunews!nrcnet0!bnrgate!scrumpy!bnrmtl@bnr.ca!john
  3. From: john@bnrmtl.bnr.ca (John Hickin)
  4. Subject: Destruction of Temporaries, Yet Another Posting
  5. Message-ID: <1992Sep2.143007.5655@bnrmtl.bnr.ca>
  6. Sender: news@bnrmtl.bnr.ca (USENET NEWS KJ)
  7. Reply-To: bnrmtl!john@larry.mcrcim.mcgill.edu
  8. Organization: Bell Northern Research Montreal, Canada.
  9. Date: Wed, 2 Sep 92 14:30:07 GMT
  10. Lines: 41
  11.  
  12. It seems to me that much of the trouble comes from exporting the details of an
  13. object's internal representation from a function that the compiler can apply
  14. automatically to a temporary ojbect.  Simple prevention can avoid most of the
  15. problems:
  16.  
  17.    1. Avoid exporting the details of an object's internal representation,
  18.       especially when the offending function can be applied automatically by
  19.       the compiler such as the famous String :: operator const char*().
  20.       It is interesting to note that the ANSI String proposal renames this
  21.       function to const char* String :: cStr().
  22.  
  23.    2. Try to write your code to avoid the generation of temporaries.  
  24.  
  25. Of course one can always generate cases where recommendation 2 will fail you
  26. and I personally don't like the idea a lot as it can really cramp your style.
  27. So here is a modest proposal:
  28.  
  29.    Make temporaries const objects
  30.    Avoid problems due to their early destruction by making dangerous
  31.    value taking operations non-const.
  32.  
  33. A compiler using the const temporary approach and a thoughtful programmer
  34. can combine to make code like that of the String example safer:
  35.  
  36.    class String { public:
  37.        operator const char*(); // NON-const
  38.        String( const char* );
  39.        ...
  40.    };
  41.  
  42.    String h( "hello " ), w( "world" );
  43.    const char* p = h + w;
  44.    //
  45.    //  compiler flags this statement:
  46.    //     Error: non-const member function applied to (const) temporary object.
  47.  
  48. Of course this could break a lot of existing code.
  49.  
  50. -- 
  51. John Hickin      Bell-Northern Research, Montreal, Quebec
  52. (514) 765-8888   bnrmtl!john@larry.mcrcim.mcgill.edu
  53.