C++对象创建
我对用 C++ 创建对象有疑问。
假设我有一个名为 Employee 的类,其中包含一些数据成员和方法。
现在在 main 函数中,有时我看到开发人员使用不同的方法来创建对象,例如
Employee emp1; // 1)
Employee emp2 = new Employee // 2)
我的疑问是我们何时应该使用情况 1 以及何时使用选项 2。
I have doubt in creating objects in C++.
Say I have a class called Employee with some data members and methods.
Now in main function sometimes I have seen developers using different methods to create objects like
Employee emp1; // 1)
Employee emp2 = new Employee // 2)
My doubt is when we should use case 1 and when to use option 2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这会在堆栈中创建一个默认构造的员工。它的生命周期持续到超出范围为止。
这可能甚至无法编译,我猜你的意思是:
这会在堆中创建一个默认构造的employee,并将其地址分配给employee 指针。它的生命周期持续到对其调用
delete
为止。它们是两个完全不同的东西。在您了解更多信息之前,您可能想坚持使用第一个版本。一旦您了解了更多信息,您也应该坚持使用第一个版本,除非您知道并理解不这样做的原因。
This creates a default constructed employee at the stack. Its lifetime lasts until it goes out of scope.
This probably doesn't even compile, I guess you meant:
This creates a default constructed employee at the heap, and assigns its address to an employee pointer. Its lifetime lasts until
delete
its called on it.They are two complete different things. Until you learn more about it, you probably want to stick with the first version. Once you learn more about it, you should stick with the first version as well unless you know and understand the reasons not to.