本文介绍了指向对象的C ++指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C ++中,是否总是使用new
关键字初始化指向对象的指针?
In C++ do you always have initialize a pointer to an object with the new
keyword?
或者您也可以拥有它:
MyClass *myclass;
myclass->DoSomething();
我认为这是分配给堆栈而不是堆的指针,但是由于对象通常是堆分配的,所以我认为我的理论可能是错误的??
I thought this was a pointer allocated on the stack instead of the heap, but since objects are normally heap allocated, I think my theory is probably faulty??
请咨询.
推荐答案
不,您可以使用指针来堆栈分配的对象:
No, you can have pointers to stack allocated objects:
MyClass *myclass;
MyClass c;
myclass = & c;
myclass->DoSomething();
当使用指针作为函数参数时,这当然很常见:
This is of course common when using pointers as function parameters:
void f( MyClass * p ) {
p->DoSomething();
}
int main() {
MyClass c;
f( & c );
}
尽管如此,还是必须始终初始化指针.您的代码:
One way or another though, the pointer must always be initialised. Your code:
MyClass *myclass;
myclass->DoSomething();
导致这种可怕的状况,不确定的行为.
leads to that dreaded condition, undefined behaviour.
这篇关于指向对象的C ++指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!