473,745 Members | 2,138 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 << "constructo r " << 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 2971
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 << "constructo r " << 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************ **********@k70g 2000cwa.googleg roups.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::cons truct (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 << "constructo r " << 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************ **********@k70g 2000cwa.googleg roups.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

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

Similar topics

14
45858
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 on what you are using the pair for. For instance if I am using coordinates in two dimensional space then I like to use x and y. So I might as well define my own struct with x and y members in it and create a constructor so
3
1437
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
2257
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 uses map<and heavy overloading. The problem is, the output file differs from input, and for the love of me I can't figure out why ;p #include <iostream> #include <fstream> #include <sstream>
4
2380
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 my own tool (http://openswarm.sourceforge.net). I already started restructuring my code to separate the actual command implementations from the command-line scripts (which is optparser-based now) and have some ideas how to proceed. But probably...
3
3379
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, &gt ,&ltCompany&gt to display '<', '>' and '<Company>' respectively. But is there any freeware code available which could implement the above functionality without having to use &gt,&lt and such stuff???
2
1584
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 ideas?
12
5833
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
2789
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
5435
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
8970
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8795
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9486
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9277
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9214
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8218
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6057
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4827
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3286
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.