Question

I'm confused by the two different ways and I find both of them are Okay in VS.Can u let me know the nature of the difference?

Was it helpful?

Solution

The first one creates a default-constructed temporary object, and uses the the copy-constructor (if the assignment is in the declaration of A) or the copy-assignment operator to copy from the temporary object to A. Then the temporary object is destroyed.

The second creates a default-constructed object on the heap, and returns a pointer to this new object. You must later delete this object or you will have a memory leak.

OTHER TIPS

At this level of understanding, the best advice I can give you is to stay away from new. You will need it later, for more complex tasks, but don't let the fact that, for instance, Java has a new as well fool you. In C++, new opens a whole world of issues which don't exist in other languages. One could argue that it's unfortunate that the keyword is identical in different languages... :)

To be more precise, new in C++ means, among other things, that you create an object which will not be automatically removed from memory when you don't need it anymore. You must remember its location in memory via a pointer, and a pointer is a dangerous tool easy to abuse especially for unexperienced programmers.

void f()
{
    Obj *a = new Obj();
    // no automatic destruction, the object remains in memory!
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top