Cha*_*nsy 1 c++ stl unordered-map copy-constructor
我有一个 std::unordered_map ,我发现我插入其中的对象与我通过使用范围遍历从中获得的对象不同。
我怀疑这里可能发生了一些对象复制,但是在我向复制构造函数添加了一些转储之后,它根本没有被调用。
谁能告诉我插入和遍历 std::unordered_map 时后台发生了什么?
我尝试了以下代码并转储:
[结果]
mypair constuctor
mypair constuctor
string1 address:0x7ffccb813ba0
string2 address:0x7ffccb813bd0
++++++++++++++++
auto &x address:0x55fb40529378
string2: 0.5
auto &x address:0x55fb405292c8
string1: 0.3
++++++++++++++++
auto x address:0x7ffccb813c00
string2: 0.5
auto x address:0x7ffccb813c00
string1: 0.3
++++++++++++++++
Run Code Online (Sandbox Code Playgroud)
[来源]
#include <iostream>
#include <string>
#include <unordered_map>
class mypair : public std::pair<std::string,double> {
public:
mypair(std::string str, double num):std::pair<std::string,double>(str, num) {
std::cout<<"mypair constuctor"<<std::endl;
}
mypair( const mypair& ) {
std::cout<<"mypair copy constuctor"<<std::endl;
}
mypair& operator=(const mypair&) {
std::cout<<"mypair copy assignment"<<std::endl;
return *this;
}
};
int main ()
{
std::unordered_map<std::string,double> myMap;
mypair string1 ("string1", 0.3);
mypair string2 ("string2", 0.5);
std::cout << "string1 address:" << &string1 << std::endl;
std::cout << "string2 address:" << &string2 << std::endl;
std::cout <<"++++++++++++++++"<< std::endl;
myMap.insert (string1);
myMap.insert (string2);
for (auto& x: myMap) {
std::cout << "auto &x address:"<< &x << std::endl<< x.first << ": " << x.second << std::endl;
}
std::cout <<"++++++++++++++++"<< std::endl;
for (auto x: myMap) {
std::cout << "auto x address:"<< &x << std::endl<< x.first << ": " << x.second << std::endl;
}
std::cout <<"++++++++++++++++"<< std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您没有看到对 的复制构造函数的任何调用mypair,因为这不是 内部使用的对类型std::unordered_map。
using value_type = std::pair<const Key, Value>;
Run Code Online (Sandbox Code Playgroud)
...是里面实际使用的pair类型。您mypair可以隐式转换为value_type,因此应调用以下成员函数:
template< class P >
std::pair<iterator, bool> insert( P&& value );
Run Code Online (Sandbox Code Playgroud)
这既不复制也不复制分配 a ,它将根据您传递的对的内容mypair构造 a 。std::pair
如果您想尽可能减少复制和开销,您应该使用emplaceor try_emplace。
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |