This expression:
new Cat();
Creates dynamically an object of type Cat
, and you are ignoring the returned pointer (not storing it, not dereferencing, nothing). This expression:
*new Cat();
Does the same as the one above, except that you are also dereferencing the pointer returned by new
. But dereferencing a pointer per se is an operation has no side-effect.
Concretely, therefore, the effect of both expressions is the same. The important bit is that you are leaking memory twice by losing the one and only reference to the objects you create dynamically.
Keep in mind that every object created with new
must be destroyed by a corresponding call to delete
. For instance, if you stored the returned pointer this way:
Cat* pCat = new Cat();
That would allow you to do, later on:
delete pCat;
And avoid memory leaks. Also, this:
Cat& cat = *new Cat();
Would allow you to do, later on:
delete &cat;
And avoid memory leaks again. Notice, however, that this would not be an option:
Cat cat = *new Cat();
The above would still give you a memory leak. The reason is that it would copy the object obtained by dereferencing the pointer returned by new
into cat
. In other words, cat
would be a different object than (although identical to) the one the new
expression created.
The object created by the new
expression, on the other hand, would be lost - resulting in a memory leak again.
In Modern C++, it is advisable to avoid manual memory management by calling new
and delete
; rather, consider using smart pointers (which one depends on the ownership policy that you need). For instance:
#include <memory>
// ...
std::shared_ptr<Cat> pCat = std::make_shared<Cat>();
Smart pointers take care of automatically destroying the referenced object when the last smart pointer to the pointed object is destroyed.