move objects to unordered_map without creating copies

Hi experts,

I'm a beginner of C++. I have some questions while trying to insert some objects to an unordered_map.

I have a struct called "test", like below
1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct test {
    test(){
        cout<<"Construtor, object address: "<<this<<endl;
    }
    test(const test& r){
        cout<<"Copy construtor, address of this: "<<this<<", address of r:"<<&r<<endl;
    }
    test(test&& r){
        cout<<"Move construtor, address of this: "<<this<<", address of r:"<<&r<<endl;
    }
    ~test(){
        cout<<"destructor, address of this: "<<this<<endl;
    }
};


And below is my main() function, I added the output to each line as comments:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main(){
    unordered_map<int, test> map;
    test t1;                          //output: Construtor, object address: 0x7fffd7933d0b
    map.insert({1, std::move(t1)});   //output: Move construtor, address of this: 0x7fffd7933d14, address of r:0x7fffd7933d0b
                                      //        Copy construtor, address of this: 0xcdd03c, address of r:0x7fffd7933d14
                                      //        destructor, address of this: 0x7fffd7933d14
    cout<<"==============="<<endl;
    test t2;                          //output: Construtor, object address: 0x7fffd7933d0c
    map.emplace(2, t2);               //output: Copy construtor, address of this: 0xcdd07c, address of r:0x7fffd7933d0c

    cout<<"==============="<<endl;
    return 0;
    //output: destructor, address of this: 0x7fffd7933d0c
    //        destructor, address of this: 0x7fffd7933d0b
    //        destructor, address of this: 0xcdd07c
    //        destructor, address of this: 0xcdd03c
}


What I want is to move the object of test struct (t1 in case 1 and t2 in case 2) to the unordered_map, but seems in both cases the map creates copy of t1 (or t2), meaning the object in the map is a copy of t1 or t2, but not t1 or t2 themselves. So what is the correct way to move t1 and t2 to the map then?

Thanks,
Michael


map.emplace(1, std::move(t1))
Topic archived. No new replies allowed.