Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

c++ - unexpected copies with foreach over a map

I am trying to loop over the entries of a map, and I get unexpected copies. Here is the program:

#include <iostream>
#include <map>
#include <string>

struct X
{
    X()
    {
        std::cout << "default constructor
";
    }

    X(const X&)
    {
        std::cout << "copy constructor
";
    }
};

int main()
{
    std::map<int, X> numbers = {{1, X()}, {2, X()}, {3, X()}};
    std::cout << "STARTING LOOP
";
    for (const std::pair<int, X>& p : numbers)
    {
    }
    std::cout << "ENDING LOOP
";
}

And here is the output:

default constructor
copy constructor
default constructor
copy constructor
default constructor
copy constructor
copy constructor
copy constructor
copy constructor
STARTING LOOP
copy constructor
copy constructor
copy constructor
ENDING LOOP

Why do I get three copies inside the loop? The copies disappear if I use type inference:

for (auto&& p : numbers)
{
}

What's going on here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The value type of map<K,V> is pair<const K,V>; so your loop needs to convert pair<const int,X> to pair<int,X>, copying both the key and the value, to give you a reference to that type.

Using the correct type (specified explicitly, or deduced with auto) will remove the copies.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...