Article View: comp.std.c++
Article #186Destruction of Temporaries, Yet Another Posting
From: John Hickin
Date: Wed, 02 Sep 1992 14:30
Date: Wed, 02 Sep 1992 14:30
41 lines
2105 bytes
2105 bytes
It seems to me that much of the trouble comes from exporting the details of an
object's internal representation from a function that the compiler can apply
automatically to a temporary ojbect. Simple prevention can avoid most of the
problems:
1. Avoid exporting the details of an object's internal representation,
especially when the offending function can be applied automatically by
the compiler such as the famous String :: operator const char*().
It is interesting to note that the ANSI String proposal renames this
function to const char* String :: cStr().
2. Try to write your code to avoid the generation of temporaries.
Of course one can always generate cases where recommendation 2 will fail you
and I personally don't like the idea a lot as it can really cramp your style.
So here is a modest proposal:
Make temporaries const objects
Avoid problems due to their early destruction by making dangerous
value taking operations non-const.
A compiler using the const temporary approach and a thoughtful programmer
can combine to make code like that of the String example safer:
class String { public:
operator const char*(); // NON-const
String( const char* );
...
};
String h( "hello " ), w( "world" );
const char* p = h + w;
//
// compiler flags this statement:
// Error: non-const member function applied to (const) temporary object.
Of course this could break a lot of existing code.
--
John Hickin Bell-Northern Research, Montreal, Quebec
(514) 765-8888 bnrmtl!john@larry.mcrcim.mcgill.edu
Technical Details
Message-ID:
<1992Sep2.143007.5655@bnrmtl.bnr.ca>Path:
arc1-ca.pugleaf.net!sparky!uunet!cs.utexas.edu!torn!cunews!nrcnet0!bnrgate!scrumpy!bnrmtl@bnr.ca!johnShow Full Headers
Complete Article Headers
Newsgroups: comp.std.c++ Path: arc1-ca.pugleaf.net!sparky!uunet!cs.utexas.edu!torn!cunews!nrcnet0!bnrgate!scrumpy!bnrmtl@bnr.ca!john From: john@bnrmtl.bnr.ca (John Hickin) Subject: Destruction of Temporaries, Yet Another Posting Message-ID: <1992Sep2.143007.5655@bnrmtl.bnr.ca> Sender: news@bnrmtl.bnr.ca (USENET NEWS KJ) Reply-To: bnrmtl!john@larry.mcrcim.mcgill.edu Organization: Bell Northern Research Montreal, Canada. Date: Wed, 2 Sep 92 14:30:07 GMT Lines: 41