【发布时间】: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