In C++
(1)Method 1 (using new
)
MyClass* myClass = new MyClass();
myClass->MyField = "Hello world!";
- Allocates memory for the object on the free store (This is frequently the same thing as the heap)
- Requires you to explicitly
delete
your object later. (If you don't delete it, you could create a memory leak) - Memory stays allocated until you
delete
it. (i.e. you couldreturn
an object that you created usingnew
) - The example in the question will leak memory unless the pointer is
delete
d; and it should always be deleted, regardless of which control path is taken, or if exceptions are thrown.
(2)Method 2 (not using new
)
MyClass myClass;
myClass.MyField = "Hello world!";
- Allocates memory for the object on the stack (where all local variables go) There is generally less memory available for the stack; if you allocate too many objects, you risk stack overflow.
- You won't need to
delete
it later. - Memory is no longer allocated when it goes out of scope. (i.e. you shouldn't
return
a pointer to an object on the stack)
As far as which one to use; you choose the method that works best for you, given the above constraints.
Some easy cases:
- If you don't want to worry about calling
delete
, (and the potential to cause memory leaks) you shouldn't usenew
. - If you'd like to return a pointer to your object from a function, you must use
new
In Java
new是创建对象的唯一方式啊! 必须new啊!
Difference
The biggest difference is probably in use: In Java, you use new all the time for everything, and you have to, since it's the one and only way to create (class-type) objects. By contrast, in C++ you should almost never have naked new in user code(必须要和delete搭配使用). C++ has unconstrained variables, and so variables themselves can be objects, and that is how objects are usually used in C++.