Look at my previous example program and its output.
What is the output of these:
1 2 3
|
cmplex c5 = cmplex( 2, 3 );
cmplex c6( 4, 5 );
cmplex c9( cmplex( 8, 9 ) );
|
Which members were called?
Were there any lines that invoke more than one member? If yes, which situation?
Here is an another test set:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
int main()
{
cmplex c0( 0 );
cmplex c1{ 1 };
cmplex c2{ c1 };
cmplex c3 = 3;
cmplex c4 = cmplex{ 4 };
cmplex c5( cmplex{ 5 } );
cmplex c6{ cmplex{ 6 } };
cmplex c7 = cmplex( 7 );
cmplex c8 = static_cast<cmplex>( 8 );
cmplex c9 = (cmplex)9;
}
|
Here are some versions of the interface of the cmplex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
// A
cmplex( int );
cmplex( const cmplex & );
cmplex( cmplex && );
// B
cmplex( int );
cmplex( const cmplex & );
// cmplex( cmplex && );
// C
cmplex( int );
// cmplex( const cmplex & );
cmplex( cmplex && );
// D
cmplex( int );
cmplex( cmplex & );
cmplex( cmplex && );
// E
cmplex( int );
cmplex( cmplex & );
// cmplex( cmplex && );
|
The A, B, and D do compile and produce:
ctor B 0 42
ctor B 1 42
copy ctor 1 42
ctor B 3 42
ctor B 4 42
ctor B 5 42
ctor B 6 42
ctor B 7 42
ctor B 8 42
ctor B 9 42 |
The C compile fails only on
cmplex c2{ c1 };
with:
In function 'int main()':
error: use of deleted function 'constexpr cmplex::cmplex(const cmplex&)'
note: 'constexpr cmplex::cmplex(const cmplex&)' is implicitly declared as deleted because 'cmplex' declares a move constructor or move assignment operator |
The E compile fails for c3-c9.
* The
cmplex c2{ c1 };
clearly requires a copy constructor.
It does not care whether constructor takes const or non-const reference, because
c1
is not a temporary.
* The compiler does provide a copy constructor
cmplex::cmplex(const cmplex&)
(unless prevented). Note the
const
.
* All the other lines seem to call
cmplex::cmplex(int)
and nothing else. However, if there is
only
cmplex::cmplex(cmplex &)
and neither
cmplex::cmplex(const cmplex&)
nor
complex::cmplex( cmplex && );
available, then they fail to compile.
Is there a temporary? Yes and no.
Formally either copy construction or move construction from temporary is used for c3-c9, but it is optimized out.