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:
The reasons to use dynamic storage include (but probably not limited to)
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 ++指针对象与非指针对象