指向对象的 C 指针

新手上路,请多包涵

在 C++ 中,您是否总是必须使用 new 关键字初始化指向对象的指针?

或者你也可以这样:

 MyClass *myclass;

myclass->DoSomething();

我认为这是分配在堆栈而不是堆上的指针,但由于对象通常是堆分配的,我认为我的理论可能有问题?

请指教。

原文由 Tony The Lion 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 830
2 个回答

不,您可以拥有指向堆栈分配对象的指针:

 MyClass *myclass;
MyClass c;
myclass = & c;
myclass->DoSomething();

这在使用指针作为函数参数时当然很常见:

 void f( MyClass * p ) {
    p->DoSomething();
}

int main() {
    MyClass c;
    f( & c );
}

但是,无论如何,必须始终初始化指针。你的代码:

 MyClass *myclass;
myclass->DoSomething();

导致可怕的情况, 未定义的行为

原文由 anon 发布,翻译遵循 CC BY-SA 2.5 许可协议

首先我需要说你的代码,

 MyClass *myclass;
myclass->DoSomething();

将导致 未定义的行为。因为指针“myclass”没有指向任何“MyClass”类型的对象。

在这里,我给你三个建议:-

选项 1:- 您可以简单地在堆栈上声明和使用 MyClass 类型对象,如下所示。

 MyClass myclass; //allocates memory for the object "myclass", on the stack.
myclass.DoSomething();

选项 2:- 通过使用 new 运算符。

 MyClass *myclass = new MyClass();

这里会发生三件事。

i) 为堆上的“MyClass”类型对象分配内存。

ii) 为堆栈上的“MyClass”类型指针“myclass”分配内存。

iii) 指针“myclass”指向堆上“MyClass”类型对象的内存地址

现在您可以在通过“->”取消引用指针后使用指针访问对象的 成员函数

myclass->DoSomething();

但是您应该在从范围返回之前释放分配给堆上“MyClass”类型对象的内存,除非您希望它存在。否则会导致 内存泄漏

 delete myclass; // free the memory pointed by the pointer "myclass"

选项 3:- 您也可以执行以下操作。

 MyClass myclass; // allocates memory for the "MyClass" type object on the stack.
MyClass *myclassPtr; // allocates memory for the "MyClass" type pointer on the stack.
myclassPtr = &myclass; // "myclassPtr" pointer points to the momory address of myclass object.

现在,指针和对象都在堆栈上。现在,您不能将此指针返回到当前范围之外,因为指针和对象的分配内存都将在超出范围时被释放。

总而言之,选项 1 和 3 将在堆栈上分配一个对象,而只有选项 2 将在堆上分配。

原文由 Malith 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题