Topic: Lifetime of default argument


Author: Nathan Myers <ncm@cantrip.org>
Date: 1996/11/01
Raw View
Stan Sulsky wrote:
>
> In the following, what should be the lifetime of the T used to
> construct y?  The 2 compilers I have handy disagree.  One has
> the T being destructed before entry to Y's ctor; the other after
> it's completion. I've been unable to deduce the answer from the DWP.
> Perhaps I've been looking in the wrong places :)
>
> A related question: if f() throws, is a T leaked?
>
> struct T {
>     T()  { cout << "T\n";  }
>    ~T()  { cout << "~T\n"; }
> };
> struct X {
>     X(T t = T()) { cout << "X\n"; }
>    ~X()          { cout << "~X\n"; }
> };
> struct Y : public X {
>     Y()  { cout << "Y\n"; f(); }
>    ~Y()  { cout << "~Y\n"; }
>    void f() {;}
> };
> int main() { Y y; return 0; }

The lifetime of "t" is that of the "full expression" in which it
appears.  Here, the expression where it "appears" is generated
implicitly,
as if you had written:

  Y() : X(T()) { cout << "Y\n"; f(); }

Therefore, you should see "~T" before "Y".  No temporary is
(correctly) leaked, regardless of its lifetime, unless the
program aborts.

Nathan Myers
ncm@cantrip.org
---
[ comp.std.c++ is moderated.  To submit articles: Try just posting with your
                newsreader.  If that fails, use mailto:std-c++@ncar.ucar.edu
  comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
  Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
  Comments? mailto:std-c++-request@ncar.ucar.edu
]





Author: Stan Sulsky <sjs@curtech.com>
Date: 1996/10/29
Raw View
In the following, what should be the lifetime of the T used to
construct y?  The 2 compilers I have handy disagree.  One has
the T being destructed before entry to Y's ctor; the other after
it's completion. I've been unable to deduce the answer from the DWP.
Perhaps I've been looking in the wrong places :)

A related question: if f() throws, is a T leaked?

struct T {
    T()  { cout << "T\n";  }
    T()  { cout << "~T\n"; }
};
struct X {
    X(T t = T()) { cout << "X\n"; }
   ~X()          { cout << "~X\n"; }
};
struct Y : public X {
    Y()  { cout << "Y\n"; f(); }
   ~Y()  { cout << "~Y\n"; }
   void f() {;}
};
int main() { Y y; return 0; }


--
Stan Sulsky
          Current Technology, Inc.  |   -- sjs@curtech.com --
          97 Madbury Rd.            |   (603) 868-2270 - voice
          Durham, NH 03824   USA    |   (603) 868-1352 - fax
---
[ comp.std.c++ is moderated.  To submit articles: Try just posting with your
                newsreader.  If that fails, use mailto:std-c++@ncar.ucar.edu
  comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
  Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
  Comments? mailto:std-c++-request@ncar.ucar.edu
]