On Sun, 14 Oct 2018 16:27:48 -0400
Sam <
s...@email-scan.com> wrote:
>
woodb...@gmail.com writes:
>
> >
> > I saw the following here:
> >
https://en.cppreference.com/w/cpp/language/noexcept_spec
> >
> > struct A{
> > A(int = (A(5),0))noexcept;
> > A(const A&)noexcept;
> > A(A&&)noexcept;
> > ~A();
> > };
> >
> > What is the first constructor doing? Thanks.
>
> The first constructor takes an optional int parameter. If not passed, the
> default value of the int parameter is
>
> (A(5), 0)
>
> This expression first construct a temporary A object, this time passing the
> first parameter as 5, then this gets destroyed by the comma operator, and
> the whole expression evaluates to 0, thus constructing the object with the
> int parameter's value set to 0.
On a minor quibble: the lifetime of the temporary is not destroyed by
the comma operator. According to §12.2/3 of C++14 "Temporary objects
are destroyed as the last step in evaluating the full-expression (1.9)
that (lexically) contains the point where they were created".
According to §1.9/10 "A full-expression is an expression that is not a
subexpression of another expression". This includes the entire
expression (A(5), 0). I think it also includes the lifetime of the
constructor of the A object which is initialized by this expression,
because any temporaries created on evaluating the arguments of a
constructor or other function last during the execution of the
function. This would seem to be confirmed by the code below which
prints:
In constructor with with value 5
In constructor with with value 0
Destroying object with value 5
Destroying object with value 0
#include <iostream>
struct A{
int i_;
A(int i = (A(5),0)) noexcept : i_(i)
{
std::cout << "In constructor with with value " << i << std::endl;
}
A(const A&) noexcept {}
A(A&&) noexcept {}
~A()
{
std::cout << "Destroying object with value " << i_ << std::endl;
}
};
int main ()
{
A a;
}