C++ Pointer Objects vs. Non Pointer Objects

Possible Duplicate:
Why would you ever want to allocate memory on the heap rather than the stack?

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

Test2 t3;
t3.test();

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?

Found answer here:

  • 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)

  • Manual control of the objects lifetime - the object will live until you explicitly destroy it
  • Creating as many objects as necessary, when the final number of objects is only known at run-time (like number of nodes in a tree or number of elements in an array).
  • Run-time control of the object's type (like actual type of polymorphic object).
  • 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).


    If you need an object to outlive the scope it was created in, then one of the solutions would be to create it on the Heap. In which case you would need a pointer. There are other reasons too, this is the most common.

    Another reason to use pointers is for "out" parameters. Granted you could use references, but many prefer to use pointers since it obviates the modification of the parameter at the call site. foo(var); vs foo(&var);

    Also, pointers can be used to either pass or return an object which may or may not exist. For example: T *foo(); // returns a pointer to an object or NULL if none exists T *foo(); // returns a pointer to an object or NULL if none exists .

    The list goes on and on really.


    如果你有一个非常大的对象(例如一个非常大的缓冲区作为成员),你可能不想在堆栈上分配它,因为堆栈空间是有限的,在这种情况下,你需要在堆上分配new operator。

    链接地址: http://www.djcxy.com/p/13796.html

    上一篇: 创建C ++对象

    下一篇: C ++指针对象与非指针对象