Re: weeding out c++ keywords from sys/sys

From: Christoph Mallon <christoph.mallon_at_gmx.de>
Date: Tue, 17 Feb 2009 10:26:54 +0100
Andrew Reilly schrieb:
> On Mon, Feb 16, 2009 at 10:57:12AM +0200, Andriy Gapon wrote:
>> on 16/02/2009 07:56 Andrew Reilly said the following:
>> This is the first time in my life that I hear about temporary objects on 
>> the heap and/or memory leaks through temporary objects. Either you are 
>> remembering a bug in some ancient C++ compiler or you are referring to 
>> some buggy code.
> 
> Well, code that results in a memory leak (or dangling reference)
> is buggy by definition, but how to avoid it, in general?  I'm
> not about to write some examples for the purpose of this
> discussion, so google searches will have to do.
> 
> The first google search that I did for "C++ argument promotion
> temporary objects" came up with this link:
> http://www.icce.rug.nl/documents/cplusplus/cplusplus09.html
> 
> If you skip down to the StringArray example, you can see that
> a new String object is automatically constructed to cast the
> char* to fit the String &operator[](size_t idx) method.  Now,
> in this instance the constructed object has somewhere to go: a
> reference is being stored in the array.  So the temporary object
> must have been constructed on the heap.  But other methods on
> other objects may require String arguments, invoking the same
> constructor, but they might not record the reference and so it
> won't be cleaned up later.  Or will it?

Uh, your observation is wrong.
I guess you talk about the line
	sa[3] = "hello world";
because this is the only line, which includes vaguely something like a 
char*[0].
The text describes in detail what happens. Actually there are no 
temporary objects involved.
First sa[3] is evaluated. The left hand side of the [] operator is a 
StringArray and the right hand side is an integer literal. The 
overloaded [] operator in class StringArray fits here, so we get a 
reference to a String, i.e. a String&, as result.
Then there is the = operator. On the left side is a String& and on the 
right side (after default conversion) a const char*.
We look in class String and find an overloaded = operator, which takes a 
const char* as second argument, so this one is called.
The sa[3] part knows nothing at all about the string literal later. The 
string literal knows nothing about the sa[3] either. Their only 
connection is the = operator, which knows both its operands, of course.
End of story.


[0] A string literal is of type const char[] and there is a deprectaed 
conversion from string literals to char*, but this is not necessary 
here, because we only need a const char* which is fine.
Received on Tue Feb 17 2009 - 08:26:58 UTC

This archive was generated by hypermail 2.4.0 : Wed May 19 2021 - 11:39:42 UTC