Both are not same!
First gives you a Undefined behavior[Ref 1:] or a memory leak while second doesn't if you call delete
later.
MyClass myObject = *new MyClass();
Allocates a object of type MyClass
on freestore and then copies that object to myObject
. You lose the pointer to the dynanically allocated object and thus can never deallocate it.
If MyClass
destructor has side effects and your program depends on those side effects then it gives you Undefined Behavior if not then what you have is a simple plain memory leak.
MyClass *myObject = new MyClass();
Allocates a object of type MyClass
on freestore and the points myObject
to the address where the dynamically allocated object is placed. You still have the pointer to the object, which you can deallocate by calling delete
later on.
If your question is, what is the best way to do this,
The answer is to not use dynamically allocated object at all:
MyClass obj;
Good Read:
Why should C++ programmers minimize use of 'new'?
[Ref 1:]
C++11 Standard: 3.8.4:
A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor. For an object of a class type with a non-trivial destructor, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; however, if there is no explicit call to
the destructor or if a delete-expression (5.3.5) is not used to release the storage, the destructor shall not be implicitly called and any program that depends on the side effects produced by the destructor has undefined behavior.