将局部变量向量分配给map<int , std::vector<int>> m1in foo(),希望一旦超出范围,就无法访问s1的值.但事实并非如此.看起来向量中的元素存储在堆内存中,局部变量s1存储在堆栈中.当s1存储在map中时,看起来它分配了一个新的堆内存并将值复制到它.我的理解是对的吗?我打印foo中每个向量元素的地址以及map中每个向量元素的地址.
#include <iostream>
#include <map>
#include <set>
#include<vector>
using namespace std;
std::map<int , std::vector<int>> m1;
void foo(){
    vector<int> s1 = { 10, 20, 30, 40 };
    cout << "local var address: " << &s1 << "\n";
    cout << "Element address " << &s1[0] << "  " << &s1[1] << " "
         << &s1[3] << "  " << &s1[4] << "\n";
    m1[1] = s1;
}
int main() {
    foo();
    cout << "\nElement value and address in map:\n";
    for (auto it = m1[1].begin(); it != m1[1].end();it++) {
        cout << *it << " " << &m1[1][*it] << "\n";  
    }
    return 0;
}
output:
local var address: 0x7fff41714400
Element address 0xc07c20  0xc07c24 0xc07c2c  0xc07c30
Element value and address in map:
10 0xc08cc8
20 0xc08cf0
30 0xc08d18
40 0xc08d40