将 NULL 引用指针传递给另一个 class 的内存分配函数

Passing a NULL reference pointer to another class's function for memory allocation

我有 2 个 classes,Class A 和 Class B。

从 A::fun1() 开始,我尝试传递一个 NULL 指针作为对 B::fun2() 的引用。我希望 B::fun2() 为我的引用指针动态分配内存并将其返回给 Class A.

当我尝试这样做时,我的程序崩溃了。但是,当我在 Class A 中分配内存并将其传递给 B 时,一切正常。

是否不能传递一个 Null 指针作为对另一个 class 的引用并用分配给它的一些内存取回它?

下面是我试过的代码。

结构 X:

struct X
{
    char symbol;
    uint32_t number;
};

Class答:

class A
{
    public:
        A();
        void fnA();
        void printA();

    private:
        X*  _objAx;
};

A::A():
   _objAx(0)
{ }

void
A::fnA()
{
    //_objAx = new X();   //<---- Uncommenting this line make the program work.
    B::create(this,
              _objAx);    // Passing the NULL pointer as reference
}

void
A::printA()
{
    cout << "Sym: " << _objAx->symbol << "; Num: " << _objAx->number << endl;
}

Class乙:

class B
{
    public:
        static void create(A*   pObjA,
                           X*   &objX);
        void fnB();

    private:
        B(A* pObjA, X* &objX);

        A*  _pObjA;
        X*  _objBx;
};

B::B(A*     pObjA,
     X*&    objX):
   _pObjA(pObjA),         // Pointer to Class A in order to call A::printA() later
   _objBx(objX)           // The NULL pointer got from Class A
{   }

void
B::create(A*    pObjA,
          X*&   objX)
{
    B* obB = new B(pObjA,
                   objX);

    obB->fnB();
}

void
B::fnB()
{
    // Commenting out the below line and doing memory allocation in Class A, 
    // makes the program work.
    _objBx = new X();   

    _objBx->symbol = 'p';
    _objBx->number = 30;
    // Following line crashes the program
    _pObjA->printA();
}

主要:

int main()
{
    A *ob = new A();
    ob->fnA();
    return 0;
}

_objBx = new X();B成员函数中,修改B::_objBx对象。这与任何 A::_objAx;.

无关

然后 pObjA->printA(); 调用一个取消引用空指针的函数。

根据您的描述,我猜测您打算 B 改为包含 X* &_objBx; 成员。