指针的一生

Lifetime of the pointers

本文关键字:一生 指针      更新时间:2023-10-16

我正在观看与Herb Sutter一起观看Symbio C 研讨会的视频 - (A)Lifetime 20.6.2016,https://www.youtube.com/watch?v=7b75rchg7z0&t=917s

以下代码已从视频11 :: 24中撰写。示波器熄灭时,必须使P1,P2和P3指针无效。试图解释指针时,它必须给出错误。

我正在在线使用https://wandbox.org/环境。GCC和Clang都给出以下结果。这一定是错误的。

有人可以在Visual Stdio上检查相同的代码。

谢谢

#include <iostream>
using namespace std;
#include <vector>
#include <memory>
#include <cstdio>
#include <cassert>
#include <string>
#include <iterator>
#include <algorithm>
#include <array>
int* p1 = nullptr; int* p2 = nullptr; int* p3 = nullptr; 
int main() {
    {
        int i = 1;
        struct MyStruct { char a; int i; char c;} s = {'a', 2, 'c'};
        array<int,7> arr = {0,1,2,3,4,5,6};
        p1 = &i;
        p2 = &s.i;
        p3 = & arr[2];
        *p1 =*p2= *p3 = 42;
        cout << *p1 << *p2 << *p3 << endl;
    }
    *p1 = 1; // This must give error
    *p2 = 2;
    *p3 = 3;
    cout << *p1 << *p2 << *p3 << endl;
}

这是输出:

424242
123

代码的行为是不确定的

在第一个cout语句之后,指针是悬挂。他们指出的变量具有自动存储持续时间,现在不超出范围。

一个C 编译器是不需要发布诊断(在编译时不能总是识别悬挂的指针),尽管如果您设置了适当的标志,则有些人会警告您。您可以将未定义行为的来源减少到

int main()
{
    int* p;
    {
        int n;
        p = &n;
    }
    *p = 0; // oops
}

视觉C 17也无法检测到未定义的行为,并给出相同的输出。