home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!olivea!mintaka.lcs.mit.edu!ai-lab!life.ai.mit.edu!tmb
- From: tmb@arolla.idiap.ch (Thomas M. Breuel)
- Newsgroups: comp.lang.c++
- Subject: Re: destruction of temporaries
- Message-ID: <TMB.92Aug14212640@arolla.idiap.ch>
- Date: 15 Aug 92 01:26:40 GMT
- References: <46140@sunquest.UUCP>
- Sender: news@ai.mit.edu
- Reply-To: tmb@idiap.ch
- Followup-To: comp.lang.c++
- Organization: IDIAP (Institut Dalle Molle d'Intelligence Artificielle
- Perceptive)
- Lines: 53
- In-reply-to: bill@sunquest.UUCP's message of 12 Aug 92 23:31:55 GMT
-
-
- One suggestion is to promulgate stylistic guidelines which caution
- against troublesome usage. For example, Jim Adcock has suggested
- (<70784@microsoft.UUCP>) "NEVER rely on unnamed temporaries to do
- anything...", but this would seem to erode the expressiveness of the
- language: constructs like "foo(x + y)" and "foo()[i]" would no longer
- be permissible. Henricson & Nyquist suggest "Do not write code which is
- dependent on the lifetime of a temporary object" but this seems too
- vague, especially for novice programmers, and seems to require us to
- know the details of the implementation. What *specific* guidelines
- would you suggest for avoiding potential problems with unnamed tem-
- poraries?
-
- I think any of these problems can only occur if you use pointers to
- temporary objects, or pointers to their contents.
-
- Assume the following definitions are in effect:
-
- Str::operator char*() ...
- Str operator+(Str&,Str&) ...
- void f(char*) ...
- void g(Str*) ...
- char *Str::h() ...
-
- Then, the following expressions are bad:
-
- (1) f((char*)(x+y));
- (2) g(&(x+y));
- (3) f((x+y).h());
- (4) f(x+y);
-
- (Str::pointer() returns some pointer to the interior of the object).
-
- Now, (1) and (2) can be avoided by not casting to a pointer types or
- taking the address of anything other than a variable.
-
- (3) is a little trickier. Generally, any member function that returns
- a pointer type should be viewed with suspicion. But you really have to
- know what you are doing:
-
- char *Str::h1() { return new char; }
- char *Str::h2() { return this->data; }
-
- Of these, h1 is OK, while h2 could fail for a temporary. The same is
- true for functions that return pointers and take reference arguments:
-
- char *h3(Str &x) { return x.data; }
-
- (4) can be avoided by not defining cast operators that convert your
- class to a pointer type; doing so is inviting trouble, even if it
- looks cute.
-
- Thomas.
-