变量超出范围后如何保留向量值?

How vector value is retained after the variable goes out of scope?

本文关键字:保留 向量 何保留 范围 变量      更新时间:2023-10-16

>在foo((中将局部变量向量分配给map<int , std::vector<int>> m1,希望s1的值一旦超出范围就无法访问。但事实并非如此。看起来矢量中的元素存储在堆内存中,局部变量 s1 存储在堆栈中。当 S1 存储在 Map 中时,看起来它分配了一个新的堆内存并将值复制到其中。我的理解是对的吗? 我正在 foo 中打印每个矢量元素的地址以及地图中每个矢量元素的地址。

#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

当你执行m1[1] = s1;时,你正在调用m1[1]的赋值运算符。如果点击该链接,则调用第一个实例,cppreference 将其描述为:

1( 复制赋值运算符。将内容替换为其他内容的副本。

(强调我的(

所以你正在查看两个完全不同的向量和两个完全不同的项目集的地址。比较它们是没有意义的。

std::map<int , std::vector<int>>

std::vector<int>value_type。这意味着存储在地图中的每个项目都包含这样的矢量对象。

它不包含对向量的引用,也不包含对向量的指针,它实际上是一个对象。

这意味着,如果在地图外部创建矢量并将其分配给地图元素,则必须移动或复制该矢量。