I learned C# first, and now I\'m starting with C++. As I understand, operator new
in C++ is not similar to the one in C#.
Can you explain the reason of
Well, you create a memory leak if you don't at some point free the memory you've allocated using the new
operator by passing a pointer to that memory to the delete
operator.
In your two cases above:
A *object1 = new A();
Here you aren't using delete
to free the memory, so if and when your object1
pointer goes out of scope, you'll have a memory leak, because you'll have lost the pointer and so can't use the delete
operator on it.
And here
B object2 = *(new B());
you are discarding the pointer returned by new B()
, and so can never pass that pointer to delete
for the memory to be freed. Hence another memory leak.