小编Shi*_*ang的帖子

使用'auto'进行迭代时,'&'符号会起什么作用

最近我在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++ for-loop reference auto c++11

3
推荐指数
3
解决办法
199
查看次数

shared_ptr的机制

我不小心在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)

c++ pointers shared-ptr

0
推荐指数
1
解决办法
204
查看次数

标签 统计

c++ ×2

auto ×1

c++11 ×1

for-loop ×1

pointers ×1

reference ×1

shared-ptr ×1