?
=?ISO-8859-1?Q?Szabolcs_Horv=E1t?=
Consider the attached example program: an object of type 'A' is inserted
into a 'map<int, A> m;'. Why does 'm[0];' call the copy constructor of
'A' twice in addition to a constructor call?
The constructors and copy constructors in 'A' report when they are
called. 'whoami' is just a unique identifier assigned to every object of
type 'A'. The output of the program is:
constructor 0
constructor 1
copy cons 2 from 1
copy cons 3 from 2
destructor 2
destructor 1
assignment 3 from 0
destructor 0
destructor 3
I would expect one constructor call to be sufficient for creating an
object inside the map. Why is it necessary to copy twice the initially
created object?
I'd expect the following output:
constructor 0
constructor 1
assignment 1 from 0
destructor 0
destructor 1
(I tried this with both g++ and the digital mars compiler.)
-- Szabolcs
-----
#include <iostream>
#include <map>
using namespace std;
int counting_As = 0;
class A {
int whoami;
public:
A() {
whoami = counting_As++;
cout << "constructor " << whoami << endl;
}
~A() {
cout << "destructor " << whoami << endl;
}
A(const A &p) {
whoami = counting_As++;
cout << "copy cons " << whoami << " from " << p.whoami << endl;
}
A & operator = (const A &p) {
cout << "assignment " << whoami << " from " << p.whoami << endl;
return (*this);
}
};
int main() {
map<int, A> m;
A a;
m[0] = a;
return 0;
}
into a 'map<int, A> m;'. Why does 'm[0];' call the copy constructor of
'A' twice in addition to a constructor call?
The constructors and copy constructors in 'A' report when they are
called. 'whoami' is just a unique identifier assigned to every object of
type 'A'. The output of the program is:
constructor 0
constructor 1
copy cons 2 from 1
copy cons 3 from 2
destructor 2
destructor 1
assignment 3 from 0
destructor 0
destructor 3
I would expect one constructor call to be sufficient for creating an
object inside the map. Why is it necessary to copy twice the initially
created object?
I'd expect the following output:
constructor 0
constructor 1
assignment 1 from 0
destructor 0
destructor 1
(I tried this with both g++ and the digital mars compiler.)
-- Szabolcs
-----
#include <iostream>
#include <map>
using namespace std;
int counting_As = 0;
class A {
int whoami;
public:
A() {
whoami = counting_As++;
cout << "constructor " << whoami << endl;
}
~A() {
cout << "destructor " << whoami << endl;
}
A(const A &p) {
whoami = counting_As++;
cout << "copy cons " << whoami << " from " << p.whoami << endl;
}
A & operator = (const A &p) {
cout << "assignment " << whoami << " from " << p.whoami << endl;
return (*this);
}
};
int main() {
map<int, A> m;
A a;
m[0] = a;
return 0;
}