473,394 Members | 2,071 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Why are there *three* constructor calls when inserting an item intoa map<>?


Consider the attached example program: an object of type 'A' is inserted
into a 'map<int, Am;'. 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, Am;
A a;
m[0] = a;
return 0;
}
Oct 8 '06 #1
10 2936
Szabolcs Horvát wrote:
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
You need to copy it at least one time to put it into the map, otherwise
your container doesn't contain anything, it just references an object on
automatic memory (the stack).
I don't know why it copies it two times though.
Oct 8 '06 #2
loufoque wrote:
>
You need to copy it at least one time to put it into the map, otherwise
your container doesn't contain anything, it just references an object on
automatic memory (the stack).
I don't know why it copies it two times though.
Actually you need no copy constructor calls at all, because operator []
in map already creates an object with a default value ('constructor 1'
in the output), so the assignment ('assignment 1 from 0') should be
sufficient.

What I don't understand whether these copy constructor calls are a
necessity (they are present in at least two STL implementations); could
map<work without them?
Oct 8 '06 #3
Szabolcs Horvát wrote:
Consider the attached example program: an object of type 'A' is inserted
into a 'map<int, Am;'. Why does 'm[0];' call the copy constructor of
'A' twice in addition to a constructor call?
int main() {
map<int, Am;
A a;
m[0] = a;
return 0;
}
This behavior is implementation dependent, and not all compiler setting
or library implementation will give you the same results. That said,
using operator[] for first insertions on the associative containers is
not terribly efficient. It goes something like this.

V& map::operator[K const&i]{
iterator _ret= this->find(i);
if(_ret==this->end()){//not found
V _tmp; //constructor 1
// map stores std::pair<const K,Vunder the hood
std::pair _ins(i,_tmp); // copy construct 2 from 1
_ret=this->insert(_ins); // copy construct 3 from 2
//insert returns where it placed the copy
}
V& _valret=_ret->second;// the V part of the pair
return _valret;
//destructor 2
//destrutor 1
}
Now you have number 0 (the A a) and number 3 alive. And this is why you
now see assigment from 0 to 3.
Hope that helps

Oct 8 '06 #4
Szabolcs Horvát wrote:
Consider the attached example program: an object of type 'A' is
inserted into a 'map<int, Am;'. Why does 'm[0];' call the copy
constructor of 'A' twice in addition to a constructor call?
Indexing operator on a map inserts a default-constructed object,
then calls assignment on it. Insertion of a default-constructed
object can cause a copy to be created. Step through all the
functions that

m[0] = a;

cause to be called, and you will see. BTW, it should give you
the idea that using the indexing operator to insert something in
a map is not the best idea. 'std::map' has 'insert' member for
that purpose.
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, Am;
A a;
m[0] = a;
return 0;
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 8 '06 #5
la*********@nyc.rr.com wrote:
Szabolcs Horvát wrote:
int main() {
map<int, Am;
A a;
m[0] = a;
return 0;
}
This behavior is implementation dependent, and not all compiler setting
or library implementation will give you the same results.
The Standard (23.3.1.2) says that map::operator[] :
Returns: (*((insert(make_pair(x, T()))).first)).second
I'm not sure how to interpret this: does it mandate the implementation,
or does it just specify that the return value should be "equivalent to"
that expression?

Your explanation is correct of course but I suspect that this
inefficiency is required by the standard.

Oct 8 '06 #6

Pete C wrote:
la*********@nyc.rr.com wrote:
Szabolcs Horvát wrote:
int main() {
map<int, Am;
A a;
m[0] = a;
return 0;
}
This behavior is implementation dependent, and not all compiler setting
or library implementation will give you the same results.

The Standard (23.3.1.2) says that map::operator[] :
Returns: (*((insert(make_pair(x, T()))).first)).second
I'm not sure how to interpret this: does it mandate the implementation,
or does it just specify that the return value should be "equivalent to"
that expression?

Your explanation is correct of course but I suspect that this
inefficiency is required by the standard.
That it is equivalent to that expression. I dont know why the standard
is so terse - it almost looks more like LISP than C++ with all those
parens. The expanded version is easier to read, and no less difficult
for a complier to optimize.
The reason that results may differ, is that for one you could get MORE
copies in a conforming implementation. Or, perhaps that the tree used
needed to rebabalance on the insertion (most implementors choose to
implement map as an rbtree) and you would see different results. Also,
in some implementations, implementors play with move constructors --
they know that for some types they are going to make a copy and then
destroy it or otherwise overwrite it, so in a few cases, you can save a
copy.

Oct 8 '06 #7

Victor Bazarov wrote:
Szabolcs Horvát wrote:
Consider the attached example program: an object of type 'A' is
inserted into a 'map<int, Am;'. Why does 'm[0];' call the copy
constructor of 'A' twice in addition to a constructor call?

Indexing operator on a map inserts a default-constructed object,
then calls assignment on it. Insertion of a default-constructed
object can cause a copy to be created. Step through all the
functions that

m[0] = a;

cause to be called, and you will see. BTW, it should give you
the idea that using the indexing operator to insert something in
a map is not the best idea. 'std::map' has 'insert' member for
that purpose.
insert is checked so if you attempt to insert the same key twice, it
will ignore the 2nd insert. Of course the fastest is insert with hint.
If you're doing a one-time load and then subsequently just finds, a
sorted vector can be more efficient than map.

Oct 9 '06 #8
In article <11**********************@k70g2000cwa.googlegroups .com>,
la*********@nyc.rr.com wrote:
Pete C wrote:
la*********@nyc.rr.com wrote:
Szabolcs Horvát wrote:
>
int main() {
map<int, Am;
A a;
m[0] = a;
return 0;
}
This behavior is implementation dependent, and not all compiler setting
or library implementation will give you the same results.
The Standard (23.3.1.2) says that map::operator[] :
Returns: (*((insert(make_pair(x, T()))).first)).second
I'm not sure how to interpret this: does it mandate the implementation,
or does it just specify that the return value should be "equivalent to"
that expression?

Your explanation is correct of course but I suspect that this
inefficiency is required by the standard.

That it is equivalent to that expression. I dont know why the standard
is so terse - it almost looks more like LISP than C++ with all those
parens. The expanded version is easier to read, and no less difficult
for a complier to optimize.
The reason that results may differ, is that for one you could get MORE
copies in a conforming implementation. Or, perhaps that the tree used
needed to rebabalance on the insertion (most implementors choose to
implement map as an rbtree) and you would see different results. Also,
in some implementations, implementors play with move constructors --
they know that for some types they are going to make a copy and then
destroy it or otherwise overwrite it, so in a few cases, you can save a
copy.
Fwiw, I don't currently see a conforming way to reduce the number of
copies below two:

You need a copy of the default constructed element in order to form the
pair<key,value>. There's no way to construct a pair with just a copy of
the key, and default construct the value in place. And then that pair
must be copy constructed because that is the only interface available to
allocator::construct (which needs to construct from a copy), which the
map is supposed to use.

If move semantics comes to pass in C++0X, then for expensive A's, the
following will (usually) help:

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(A &&p) {
whoami = counting_As++;
cout << "move cons " << whoami << " from " << p.whoami << endl;
}
A & operator = (const A &p) {
cout << "assignment " << whoami << " from " << p.whoami << endl;
return (*this);
}
};

constructor 0
constructor 1
move cons 2 from 1
move cons 3 from 2
destructor 2
destructor 1
assignment 3 from 0
destructor 0
destructor 3

The move constructor is allowed to transfer resources from the source
object to construct itself (like auto_ptr "copy").

-Howard
Oct 9 '06 #9

Howard Hinnant wrote:
In article <11**********************@k70g2000cwa.googlegroups .com>,
la*********@nyc.rr.com wrote:
. Also,
in some implementations, implementors play with move constructors --
they know that for some types they are going to make a copy and then
destroy it or otherwise overwrite it, so in a few cases, you can save a
copy.

Fwiw, I don't currently see a conforming way to reduce the number of
copies below two:
The move constructor is allowed to transfer resources from the source
object to construct itself (like auto_ptr "copy").

-Howard
I had just finished reading
http://www.open-std.org/JTC1/SC22/WG...006/n2027.html when
I wrote this, and I was hoping that some platform actually implemented
it. Also, inside the guts of STLPort, move constructors are used for
some optimizations like this, when it involves other std defined types.
I dont think that this particular optimization is made, but my
understanding is that even though the standard seemingly writes out the
steps needed to implement the function, the intent is that behavior of
these steps is preserved, if not exactly the sequence.

Oct 10 '06 #10

Howard Hinnant wrote:
In article <11**********************@k70g2000cwa.googlegroups .com>,
la*********@nyc.rr.com wrote:
. Also,
in some implementations, implementors play with move constructors --
they know that for some types they are going to make a copy and then
destroy it or otherwise overwrite it, so in a few cases, you can save a
copy.

Fwiw, I don't currently see a conforming way to reduce the number of
copies below two:
The move constructor is allowed to transfer resources from the source
object to construct itself (like auto_ptr "copy").

-Howard
I had just finished reading
http://www.open-std.org/JTC1/SC22/WG...006/n2027.html when
I wrote this, and I was hoping that some platform actually implemented
it. Also, inside the guts of STLPort, move constructors are used for
some optimizations like this, when it involves other std defined types.
I dont think that this particular optimization is made, but my
understanding is that even though the standard seemingly writes out the
steps needed to implement the function, the intent is that behavior of
these steps is preserved, if not exactly the sequence.

Oct 10 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: Neil Zanella | last post by:
Hello, I would like to ask how come the design of C++ includes std::pair. First of all I don't think many programmers would use it. For starters, what the first and second members are depends...
3
by: mcassiani | last post by:
Hi, I need use map faster as possible (I store in the map data about open network connections). First a question, this code fragment is from "The C++ Programming........
2
by: brzozo2 | last post by:
Hello, this program might look abit long, but it's pretty simple and easy to follow. What it does is read from a file, outputs the contents to screen, and then writes them to a different file. It...
4
by: Anastasios Hatzis | last post by:
I'm looking for a pattern where different client implementations can use the same commands of some fictive tool ("foo") by accessing some kind of API. Actually I have the need for such pattern for...
3
by: ajay2552 | last post by:
Hi, I have a query. All html tags start with < and end with >. Suppose i want to display either '<' or '>' or say some text like '<Company>' in html how do i do it? One method is to use &lt,...
2
by: DaTurk | last post by:
Hi, I'm trying to hold a map of ints,and function pointers in C++ map<int, (*functPtr)(int, int)something I need to hold a list of callbacks. For some reason this syntax is not working. Any...
12
by: jabbah | last post by:
Actually I'm quite sure I've missed something trivial here, but I just can't find it. Seemingly I cannot read from a const map& I try #include <iostream> #include <map> using namespace std;
2
by: jabbah | last post by:
I have some data in a map and I want to sort it. Currently I have implemented it like this: #include <iostream> #include <map> #include <string> using namespace std; int main(){
6
by: Juha Nieminen | last post by:
joseph cook wrote: Not always. By default, yes, but you can specify other comparators, eg: std::map<int, int, std::greaterreversedMap;
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.