【问题标题】:constructor's problem to initialize pointer data member构造函数初始化指针数据成员的问题
【发布时间】:2020-09-02 12:50:25
【问题描述】:

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

#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;

提前致谢 注意-没有产生错误

【问题讨论】:

标签: c++ class pointers constructor


【解决方案1】:

你写的相当于:

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){}
};

完成

【讨论】:

  • 是的,或者explicit base(int i = 0) : apex{ new int(i) } {} 如果apex 出于某种原因确实需要成为指针。
  • 不,一般来说,这应该在std::unique_ptr&lt;int&gt; 中,然后使用std::make_unique&lt;int&gt;(i),否则很大程度上取决于它必须是指针的原因。
【解决方案2】:

我明白了。相信我,在这个愚蠢的怀疑之后,我为自己感到羞耻。

#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);
}

【讨论】:

    【解决方案3】:

    你的指针指向你没有初始化的无效地址 这将解决您要求完成的问题。

    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) 的生命周期比实例长。

    【讨论】:

    • 没有。这是错误的。 UB 潜伏在拐角处,因为apex 存储了一个悬空指针。 i 是构造函数的本地对象
    • 现在不同了,但仍然是错误的。 “确保给 ctor 的东西比实例的寿命更长”你在你的例子中没有这样做。指针仍然无效
    • 嗯,不,实际上这不会编译
    • 现在没有错,但我对这个问题的解释不同。看起来OP在写*apex = i;时想要取值而不是指针,我当然可能错了
    • 我只考虑了这部分问题。 “初始化指针数据成员时遇到问题”
    猜你喜欢
    • 1970-01-01
    • 2021-12-26
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    相关资源
    最近更新 更多