【问题标题】:Passing a NULL reference pointer to another class's function for memory allocation将 NULL 引用指针传递给另一个类的函数以进行内存分配
【发布时间】:2016-03-18 06:34:50
【问题描述】:

我有两个班,A班和B班。

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

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

是否不可能将 Null 指针作为对另一个类的引用并通过分配给它的一些内存来取回它?

下面是我试过的代码。

结构 X:

struct X
{
    char symbol;
    uint32_t number;
};

A类:

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

B类:

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

【问题讨论】:

  • X* _objBx 不是参考。
  • 这里的语义真的很复杂,不能简化一下吗? OT 而不是使用 out 参数 考虑 returning std::unique_ptr.
  • 除了在B::create() 函数结束后消失的本地指针之外,您永远不会将new B() 对象分配给任何其他对象。

标签: c++ pointers pass-by-reference


【解决方案1】:

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

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

我从您的描述中猜测您打算将B 包含X* &amp;_objBx; 成员。

【讨论】:

  • 谢谢。缺少使 _objBx 成为参考。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-09
  • 2018-09-16
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
  • 1970-01-01
  • 2012-07-03
相关资源
最近更新 更多