It is not the same thing. In most object-oriented languages, particularly ones with built in garbage collection of any kind, all objects are allocated on the heap and variables always contain a pointer to the object, not the object itself.
C++ is one of the few object-oriented languages where you can refer to an object by value.
In the case of new
you are creating an object and being given a pointer to it. You will then reference the object through the pointer and not directly. In the other case you are creating the object on the stack and the container will be storing its own copies.
Frequently, stack based copies will be referred to by reference (the whole idea behind &
as a type qualifier), but those references are understood to generally be short-lived and a copy is usually made of the thing being referenced if that thing needs to be stored for awhile.
In this case in particular, if you have a container of pointers (i.e. ::std::vector<SubElement *> c
) it stores pointers to objects and you would typically allocate them with new
. But the standard library container classes (and most other container classes) do not delete pointers for you. They do not take 'ownership' of the pointer. So you will be responsible for deleting them yourself.
If you have a container of objects (i.e. ::std::vector<SubElement> c
) then you would use the c.push_back(SubElement())
form and the container would store copies of the temporaries you were creating. The container does take ownership of those copies, and will also frequently copy them around internally. That's why objects you store by value in a container need to implement the copy constructor.
There is a way to get a container to take ownership of the pointers, but only indirectly. You can have the container store copies of objects that themselves take ownership. The standard class people use for this is ::std::tr1::shared_ptr<T>
. Your container declaration would look like: ::std::vector< ::std::tr1::shared_ptr<SubElement> > c
. You could then do: c.push_back(new SubElement());
and the container would delete the SubElement objects when it was done.
You should read up on shared_ptr
and really understand what it's doing before you use it though.