search

Home  >  Q&A  >  body text

stl - c++ map下标的执行流程是什么?

class A
{
public:
    A()
    {
        cout << "调用默认构造函数" << endl;
    }
    A(A& src)
    {
        cout << "调用拷贝构造函数"  << endl;
    }
    ~A()
    {
        cout << "调用析构函数"  << endl;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    map<int,A> mapTest;
    cout << "=========" << endl;
    mapTest[0];
    cout << "=========" << endl;
    return 0;
}

执行结果:

疑问:
使用map下标操作如果不存在key的话,会调用默认构造函数生成一个实例,为什么会调用两次拷贝构造函数呢?下标操作的具体执行流程是什么?有什么办法可以跟踪到执行流程?

PHP中文网PHP中文网2807 days ago727

reply all(3)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 13:23:07

    If the key does not exist, then map will help you generate a map<int, A>::value_type aka: pair<const int, A>(by std::make_pair), and then insert this temporarily generated pair into the map It will be reconstructed again, so there will be two copies. But now is the 21st century, and Move semantics can be used to make full use of temporary objects to reduce copies.
    You can try programming in C++11 and see what the difference is.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:23:07

    Referring to the answer of the bearded old man, I simulated the process

    map<int,A> mapTest;
    cout << "=========" << endl;
    mapTest[0];
    cout << "=========" << endl;
    cout << "1" << endl;
    A temp1;
    cout << "2" << endl;
    pair<int,A> pa = std::make_pair(1,temp1);
    cout << "3" << endl;
    mapTest.insert(pa);
    cout << "=========" << endl;

    Result:

    It is true that two temporary objects are generated, so there will be two copies and two destructions.
    Approximate process of map subscripting:
    If the key does not exist

    1.生成一个临时对象
    2.生成一个pair
    3.插入到map中

    Thanks to the bearded old man and araraloren for their answers

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 13:23:07

    Just like the bearded old man above said, construct it once, then copy it once to generate a Pair type, and finally copy it to the Map data structure
    Isn’t the execution process what you said, first look for the key, no There is a way to create an insert. The specific process is relatively complicated and involves many calls. If you want to know, you can look at the source code of map. Of course, the source code of map in VS is not written for people to see. . . You can refer to other STL map source codes
    In C++11, this operation is much less laborious. It is completed with only one construction. Of course, the Move constructor is also called. .
    Finally, generally don’t use it this way. .

    reply
    0
  • Cancelreply