最近我在C++中使用auto时遇到了非常奇怪的问题,只是...看看下面的代码片段:
我的主要功能:
#include <list>
#include <iostream>
#include <stdio.h>
int main(){
int a = 10, b = 20, c = 30;
list<int> what;
what.push_back(a);
what.push_back(b);
what.push_back(c);
read(what);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这里的功能如下:
void read(const list<int>& con){
for (auto it : con){
printf("%p\n", &it);
cout << it << endl;
}
return ;
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
0x7fffefff66a4
10
0x7fffefff66a4
20
0x7fffefff66a4
30
Run Code Online (Sandbox Code Playgroud)
那是什么呀?具有不同内容的相同地址!
更奇怪的是,如果我通过添加'&'
来修改for循环,那么:
for (auto& it : con){
Run Code Online (Sandbox Code Playgroud)
所有输出立即有意义,地址将通过迭代改变
所以我的问题是,
为什么'&'标志在这种情况下会发生变化?
我不小心在C++上发现了这个问题,但完全不知道它是怎么发生的,请查看下面的代码片段:
int main() {
int *aptr = new int(20); //Declare an integer space with 20, and aptr points to it
shared_ptr<int> a(aptr); //Declare a shared_ptr to points where aptr points
stringstream ss;
ss << a;
const char *chstr = ss.str().c_str(); // Save the address as string
void *address;
sscanf(chstr, "%p", (void **)&address); // Convert string back to pointer
a = NULL; // Free the shared pointer
cout << *reinterpret_cast<int*>(address) << endl; // Output: 0, 20 has gone
return 0;
} …Run Code Online (Sandbox Code Playgroud)