繁体   English   中英

构造函数初始化指针数据成员的问题

[英]constructor's problem to initialize pointer data member

我在初始化指针数据成员时遇到问题,即 int* apex; 在参数为 int i = 0 的构造函数中; 如*顶点=我; 但不幸的是,编译器敲到这一行后什么也没有执行。

#include <iostream>
using namespace std;

class base{
    int *apex;      
public:
    explicit base(int i = 0){
        cout << "this does executes" << endl;
        *apex = i; // <<<<<--- problem???
        cout << "this doesnt executes" << endl;
    }
};

int main(void){
    base test_object(7);
    cout << "this also doesnt executes";
}


// I know how to avoid this but i want to know what
// exactly the problem is associated with *apex = i;

预先感谢注意 - 不会产生错误

你写的相当于:

int *apex;
*apex = 42;

这是未定义的行为 (UB),其中包括编译器可能只包含停止执行或开始播放 Rick Astley 的歌曲 Never Gonna Give You Up 的代码。

甚至

int *apex = nullptr;
*apex = 42;

将是 UB,因为int*指针在通过*取消引用时必须指向有效的int

写就好了

class base{
    int apex{};      
public:
    explicit base(int i) : apex(i){}
};

并完成

我知道了。 相信我,在这种愚蠢的怀疑之后,我为自己感到羞耻。

#include <iostream>
using namespace std;

class base{
    int *apex;      
public:
    explicit base(int i = 0){
        apex = new int;
        // this is what i was supposed to do
        *apex = i;
    }
};

int main(void){
    base test_object(7);
}

您的指针指向您未初始化的无效地址这将解决您要求完成的操作。

using namespace std;

class base{
    int *apex{nullptr};      
public:
    explicit base(int& i ): apex{&i} {
        cout << "this does executes" << endl;
        cout << "this doesnt executes" << endl;
    }
};

int main(void){
    int a = 7
    base test_object(a);
    cout << "this also doesnt executes";
}

确保给予 ctor 的东西 ( int ) 比实例具有更长的生命周期。

暂无
暂无

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

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