Different methods for instantiating an object in C++

What is the difference between this:

Myclass *object = new Myclass();

and

Myclass object = new Myclass();

I have seen that a lot of C++ libraries like wxWidgets, OGRE etc use the first method... Why?


The second is wrong !

You may use

MyClass object;

That will work.

Now, concerning how to choose between these two possibilities, it mainly depends on how long your object should live. See there for a thorough answer.


Myclass *object = new Myclass(); //object is on the heap
Myclass object; //object is on the stack

如果您计划在很长一段时间内使用这些对象,并且您在堆栈上创建对象的时间较短(或范围),则可以在堆上创建对象。


Your first line is 100% correct. Unfortunately, you can't create object with your second line in c++. There are two ways to make/create an object in c++.

First one is :

MyClass myclass; // if you only need to call the default constructor    
MyClass myclass(12); // if you need to call constructor with parameters*

Second one is :

MyClass *myclass = new MyClass();// if you only need to call the default constructor
MyClass *myclass = new MyClass(12);// if you need to call constructor with parameters

In c++ if you use the new keyword, object will be stored in heap. It's very useful if you are using this object for a long time period and if you use first method, it will be stored in stack. it can be used only short time period. Notice: if you use new keyword, remember it will return pointer value. You should declare name with * . If you use second method, it doesn't delete object in the heap. You must delete by yourself using delete keyword:

delete myclass;
链接地址: http://www.djcxy.com/p/13794.html

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

下一篇: 用于在C ++中实例化对象的不同方法