简体   繁体   English

在 const Class function 中更改 class 指针的值会导致某些编译器出错,但不会在其他编译器中出错

[英]changing a value of a class pointer in const Class function gives an error in some compiler but not others

I have below code and It gives an error as "segmentation fault" in some compiler but for other compilers it gives "40" as output.我有下面的代码,它在某些编译器中给出了“分段错误”的错误,但对于其他编译器,它给出的“40”为 output。 Why is there difference?为什么有区别?

#include <stdio.h>

class A{
    int *ptr;
    public:
    void set(int val) const;
};
void A::set(int val) const{
    *ptr = val;
    printf("%d", *ptr);
}

int main(){
    A a;
    a.set(40);
    return 0;
}

ptr is an uninitialized pointer. ptr 是一个未初始化的指针。 When you deference an unitialized pointer, it's undefined behaviour, anything can happen.当您尊重一个未初始化的指针时,它是未定义的行为,任何事情都可能发生。

You should initialize ptr in the constructor您应该在构造函数中初始化 ptr

class A{
    int *ptr;
    public:
    A();
    void set(int val) const;
    
};

A:A()
{
    ptr = new int();
} 


A:~A()
{
   delete ptr;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM