在初始化列表中使用解除引用的指针初始化变量

时间:2018-05-28 14:24:14

标签: c++ pointers constructor initializer-list

所以我将一些代码从C更改为C ++,因此我必须为所有结构/类添加所有构造函数析构函数。

所以考虑一下以下的模型结构

struct CAddition {
    int x;
    int *foo;
    int y;
    int c;
    int z[3];
    int result() { 
        return x + y; 
    }
    CAddition();
    ~CAddition();
};

现在在初始化函数的某个地方,变量y被初始化,其值为foo,指向的有点像这样

int func_test(CAddition *temp)
{
    temp->y = *temp->foo;
    return temp->y;
}

我已经怀疑了,因为指针foo没有指向任何东西(或者让我们说在垃圾记忆位置)但是我仍然以某种方式删除了intilization函数我试图初始化y 在我的初始化列表中

CAddition::CAddition()
    : x(0)
    , foo(nullptr) // can be simply foo() both are the same as far as i know
    , y(*foo)
    , z()
    ,c(result())
{
}

显然编程崩溃是因为foo是一个空指针,我的问题是,是否有某种方法或解决方法我可以用解除引用的指针y初始化foo所以它不会碰撞

P.S我尝试调用func_test并因为同样的原因而崩溃,因为foo是nullptr

CAddition test_fun;
add_res = func_test(&test_fun);

0 个答案:

没有答案