指针的生命周期

时间:2017-12-05 09:40:14

标签: c++

我正在观看带有Herb Sutter的Symbio C ++研讨会视频 - (Thrill of 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

2 个答案:

答案 0 :(得分:8)

代码的行为是 undefined

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

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

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

答案 1 :(得分:0)

Visual C ++ 17也无法检测到未定义的行为,并提供相同的输出。