[英]c++ reference to pointer
I have the following pseudocode: 我有以下伪代码:
function1()//Gets called on startup
{
myclass* obj;
function2(obj);
obj->doSomething();//crashes here!
}
function2(myclass*& ret)
{
myclass* nobj = &myclass();
nobj->doSomething();//Does not crash
ret = &nobj;
}
It would appear that even though I am setting ret to point to nobj, when I try to operate on obj (which should be pointing to nobj, as ret is a reference to obj), my program crashes! 看起来即使我设置ret指向nobj,当我尝试操作obj(应该指向nobj,因为ret是对obj的引用)时,我的程序崩溃了! Clearly I am doing something wrong, anyone know what it is? 显然,我做错了什么,有谁知道它是什么?
You are taking the address of a temporary by doing &myclass()
, which is a no-no because the temporary is destroyed at the end of the expression, and your compiler shouldn't allow it. 您正在通过执行&myclass()
临时的地址,这是禁止的,因为临时在表达式的末尾被销毁,并且您的编译器不应该允许它。
Although your compiler is nonconformant in that area already, you are going on to use a destructed object, which is undefined behaviour and is why your code crashes. 虽然您的编译器已经在该区域中不一致,但您将继续使用被破坏的对象,这是未定义的行为,这也是您的代码崩溃的原因。
Also, I'm not sure how you are assigning a pointer to a pointer to a myclass
( &nobj
) to a pointer to a myclass
( ret
). 另外,我不确定你是如何将指向myclass
( &nobj
)的指针分配给指向myclass
( ret
)的指针。 It shouldn't compile. 它不应该编译。
try with: 尝试:
myclass *obj = new myclass();
obj->doSomething();
delete obj;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.