Initialization and assignement
Please consider the following code, which I have reduced from an
example in which I had initially employed debug print statements to
analyse which ctors/operators are called during the various
initializations and/or assignments.
class A {
int i_;
public:
A(): i_(0) { }
A(int i): i_(i) { }
A(const A& a) { i_ = a.i_; }
A& operator=(const A& a) { i_ = a.i_; return *this; }
A& operator=(const int i) { i_ = i; return *this; }
};
int main()
{
A a0; // #0
A a1(1); // #1
A a2(A(2)); // #2
A a3 = 3; // #3
A a4; // #4.a
a4 = 4; // #4.b
A a5(a0); // #5
return 0;
}
In terms of results, I found through debugging that most of these
resolved as I would have expected, but a couple of them perhaps not
so.
The straightforward ones seemed to be:
#0: initialization of a0 using the 0-arg ctor;
#1: initialization of a1 using the 1-arg ctor;
//...
#4: a: initialization of a4 using the 0-arg ctor;
b: assignment to a4 using operator=(const int);
#5: initialization of a5 using the copy ctor.
Surprisingly (to me), however, #2 did not resolve to:
#2: a: initialization of temporary using the 1-arg ctor;
b: initialization of a2 using the copy ctor
but rather the temporary + copy ctor was (apparently) optimized away
to the call:
A a2(2);
that is:
#2: initialization of a2 using the 1-arg constructor (i = 2).
Likewise, #3 resolved to:
A a3(3).
This was not totally unexpected, but I did have the slight suspicion
that it might be effected using:
#3: a: initialization of temporary using the 1-arg ctor (i = 3)
b: initialization of a3 using the copy ctor.
(That the copy assignment operator= (const A&) was not called in any
of the instances completely matched expectations based on my
understanding of the differences between initialization and
assignment.)
Given this, my question would be whether the resolutions for
initialization provided by my compiler (gcc 3.4.4, cygwin) for #2 and
#3 are what others might have expected and, in particular, whether
they are what *must* be expected to be in accordance with the
standard.
Regards
Paul Bibbings
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]