在 C++ 中,您是否总是必须使用 new
关键字初始化指向对象的指针?
或者你也可以这样:
MyClass *myclass;
myclass->DoSomething();
我认为这是分配在堆栈而不是堆上的指针,但由于对象通常是堆分配的,我认为我的理论可能有问题?
请指教。
原文由 Tony The Lion 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 C++ 中,您是否总是必须使用 new
关键字初始化指向对象的指针?
或者你也可以这样:
MyClass *myclass;
myclass->DoSomething();
我认为这是分配在堆栈而不是堆上的指针,但由于对象通常是堆分配的,我认为我的理论可能有问题?
请指教。
原文由 Tony The Lion 发布,翻译遵循 CC BY-SA 4.0 许可协议
首先我需要说你的代码,
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 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答1.6k 阅读✓ 已解决
不,您可以拥有指向堆栈分配对象的指针:
这在使用指针作为函数参数时当然很常见:
但是,无论如何,必须始终初始化指针。你的代码:
导致可怕的情况, 未定义的行为。