Topic: Point-of-destruction for actual-params passed by value


Author: lomew@emily.cs.utah.edu (Bart Robinson)
Date: 1995/04/14
Raw View
Is the point-of-destruction for the actual-params passed to a
function by value implementation defined?  If so, why?

I ask since I get different behavior for the example program
below which passes a class object by value.  With cfront 3.0 the
destructor for the object created by the copy ctor is not called
until the end of main---i.e., its lifetime is from the point of
call to the end of the enclosing scope.  But with gcc-2.5.8 the
dtor is called upon leaving `f'---i.e., its lifetime is that of
a local variable.

---------------------------------------------------------------------
#include <stdio.h>
#include <string.h>

class foo {
public:
 foo(char* n) {
  printf("foo::foo(%s)\n", n);
  strcpy(name, n);
 }
 foo(const foo& src) {
  printf("foo::foo(const foo& src), copy of %s\n",
   src.name);
  sprintf(name, "copy of %s", src.name);
 }
 ~foo() {
  printf("foo::~foo(), %s\n", name);
 }
private:
 char name[1024];
};

void f(foo c) { }

main() {
 foo a("a");
 foo b("b");

 printf("----------------- calling f(a) in new scope\n");
 { f(a); }
 printf("----------------- calling f(b)\n");
 f(b);
 printf("----------------- exiting main()\n");
}
---------------------------------------------------------------------

Given that:
 1 - "Names of formal arguments for a function are treated
     as if they were declared in the outermost block of that
     function." (_The C++ Programming Language, 2e_, p.483).
     I.e., they are like initialized automatics,
 2 - "Destructors are invoked implicitly...when an
     auto...object goes out of scope." (same source as
     (1), p.575),
and
 3 - "Destruction of auto variables declared in the block
     is done on exit from the block." (same source as
     (1), p.513),
I don't see why cfront behaves as it does.

I know that handling of temporary class objects to evaluate
arguments to a function call may be done at the compiler's
leisure (ctor and dtor must be called but doesn't matter when):
 f(g(3)); // temp to hold g(3) can be destroyed whenever
but I don't think the above program fits this category since a
just a reference to the param needs to be passed to the copy
ctor.

Thanks for reading this far!

.Bart