Topic: lifetime of temporaries in c-tor initializer lists


Author: "Bill Wade" <bill.wade@stoner.com>
Date: 1999/10/27
Raw View
Michael Greenspon wrote in message <381125D3.BEFC5B79@sequin.com>...
>Consider:
>
>class val_t {
> val_t();
> ~val_t();
> operator int() const;
>};
>
>extern val_t getVal(const char* n);
>
>class T {
> int v1, v2;
> T() : v1( getVal("v1") ), v2( getVal("v2") ) {}
>};
>
>VC++6.0 is generating code that calls the destructor val_t::~val_t() before
>calling operator int() to retrieve the converted value. This clearly seems
like
>a codegen error to me and the code has always worked on other platforms.
Would
>the standard specify anything such as a limitation on the lifetime of the
>temporary val_t returned by getVal() that would justify the compiler's
output
>and make the code incorrect as written?

It can be appropriate for ~val_t() to be called before operator int().
Remember that in return-by-value you may be getting a copy constructor
invocation, so that you get (more or less):

  val_t temp(getVal_result);
  getVal_result.~val_t();
  int v1(temp.operator int());
  temp.~val_t();

The compiler is not required to actually call the copy constructor (it can
alias getVal_result and temp).  However if it does use the copy constructor,
you'd better be sure that it does what you want.
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: Michael Greenspon <mcg@sequin.com>
Date: 1999/10/24
Raw View
Consider:

class val_t {
 val_t();
 ~val_t();
 operator int() const;
};

extern val_t getVal(const char* n);

class T {
 int v1, v2;
 T() : v1( getVal("v1") ), v2( getVal("v2") ) {}
};

VC++6.0 is generating code that calls the destructor val_t::~val_t() before
calling operator int() to retrieve the converted value. This clearly seems like
a codegen error to me and the code has always worked on other platforms. Would
the standard specify anything such as a limitation on the lifetime of the
temporary val_t returned by getVal() that would justify the compiler's output
and make the code incorrect as written?

Unfortunately this bug(if I assume it is a bug) affects a pervasive pattern in
our source and I don't have a good workaround (pulling all these initializations
out of the c-tor list would be prohibitive.) Any ideas?

Thanks
Michael
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]