Temporary default argument storage duration

M

martinezfive

Hi,
According to ISO C++ (7.11/2), "An object declared without a
storage-class-specifier at block scope or declared as a function
parameter has automatic storage duration by default."
What about temporary objects used as default function arguments?
If I have:
class A{};
void g( A &b = A() ){}
what is the storage duration of the temporary?
 
V

Victor Bazarov

Hi,
According to ISO C++ (7.11/2), "An object declared without a
storage-class-specifier at block scope or declared as a function
parameter has automatic storage duration by default."
What about temporary objects used as default function arguments?

Default arguments (the '= blah' syntax) is just another way to
initialise the argument (just as if you passed that expression in
when making the call).
If I have:
class A{};
void g( A &b = A() ){}
what is the storage duration of the temporary?

Your code is ill-formed. A reference to non-const cannot be
initialised with (bound to) a temporary. Change 'b' to be a ref
to 'const A', then your code would be OK.

The semantics (and the lifetime of the temporaries) is described
in [class.temporary]/5, they even have an example that is almost
like your code here. In short: it survives any call to 'g'. The
precise moment of that temporary's destruction cannot be determined
without seeing the code that calls 'g'.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top