[英]Inside and outside the class, why the same data has different values?
As the topic, I was confusing this question for two night.作为话题,我把这个问题混淆了两个晚上。
I tried to use function build_BDDs to modify the value of map data structure outs, but the value printed inside the function is not the same as outside the function.我尝试使用函数 build_BDDs 来修改 map 数据结构 outs 的值,但是函数内部打印的值与函数外部不一样。
I changed the bool elements of struct map_Data to int type and had the same problem.我将 struct map_Data 的 bool 元素更改为 int 类型并遇到了同样的问题。 I suspect I'm using the wrong pointer, but can't figure out what's wrong.
我怀疑我使用了错误的指针,但无法弄清楚出了什么问题。
here is my codes.这是我的代码。
#include <bits/stdc++.h>
using namespace std;
struct map_Data{
bool hi;
bool lo;
};
map<pair<int, int>, map_Data*> outs;
class MWVC{
public:
map_Data build_BDDs(map<pair<int, int>, map_Data*> & ins){
map_Data txt;
txt.hi = 1;
txt.lo = 0;
ins[make_pair(2,4)] = &txt;
cout << ins[make_pair(2,4)]->hi << ";" << ins[make_pair(2,4)]->lo << endl;
return * ins[make_pair(2,4)];
}
};
int main(){
MWVC ojb;
map_Data a;
a.hi = 1;
a.lo = 0;
outs[make_pair(1,2)] = &a;
if(outs[make_pair(1,4)]){
cout << outs[make_pair(1,4)]->hi << endl;
}
map_Data b = ojb.build_BDDs(outs);
cout << outs[make_pair(2,4)]->hi << ";" << outs[make_pair(2,4)]->lo << ";" << b.hi << ";" << b.lo << endl;
return 0;
}
and the result is结果是
1;0
0;0;1;0
Thanks advance.提前谢谢。
You build_BDDs
function stores the address of a local variable in the map.您的
build_BDDs
函数将局部变量的地址存储在地图中。 When the function returns, the memory it points to can be overwritten at any time.当函数返回时,它指向的内存可以随时被覆盖。
For this instance, just drop the pointers and let the std::map worry about memory management:对于这种情况,只需删除指针并让 std::map 担心内存管理:
map<pair<int, int>, map_Data> outs;
and change build_BDDs to:并将 build_BDDs 更改为:
map_Data build_BDDs(map<pair<int, int>, map_Data> & ins){
ins[make_pair(2,4)] = map_Data{1, 0};
cout << ins[make_pair(2,4)].hi << ";" << ins[make_pair(2,4)].lo << endl;
return ins[make_pair(2,4)];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.