C ++指针对象与非指针对象 [英] C++ Pointer Objects vs. Non Pointer Objects

查看:312
本文介绍了C ++指针对象与非指针对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:





Test2 *t2 = new Test2();
t2->test();

Test2 t3;
t3.test();

为什么要创建一个类型为Test2的指针对象?为什么不只是做非指针版本的Test2?为什么要做指针对象?

Why would I want to create a pointer object of type Test2? Why not just do non pointer version of Test2? Why would I want to do pointer objects?

找到这里的答案:

  • Why would you ever want to allocate memory on the heap rather than the stack?
  • When is it best to use a stack instead of a heap and vice versa?
  • When to use "new" and when not to in C++?
  • When should I use the new keyword in C++?
  • Proper stack and heap usage in C++
  • Stack, Static and Heap in C++

推荐答案

使用动态存储的原因包括(但不限于)

The reasons to use dynamic storage include (but probably not limited to)


  1. 控制对象生命周期 - 对象将一直存在,直到您显式销毁它

  2. 创建尽可能多的对象,当对象的最终数量只在运行时才知道树中的节点或数组中的元素数量)。

  3. 对象类型的运行时控制(如多态对象的实际类型)。

当它没有区别时,总是最好使用 t3 方法创建对象。不要使用动态内存,除非你必须。但有时你真的需要(见上述原因)。

When it makes no difference, it is always better to create the object using your t3 method. Don't use dynamic memory unless you have to. But sometimes you really have to (see the reasons above).

这篇关于C ++指针对象与非指针对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆