Calling constructors in c++ without new
I've often seen that people create objects in C++ using
Thing myThing("asdf");
Instead of this:
Thing myThing = Thing("asdf");
This seems to work (using gcc), at least as long as there are no templates involved. My question now, is the first line correct and if so should I use it?
Both lines are in fact correct but do subtly different things.
The first line creates a new object on the stack by calling a constructor of the format Thing(const char*)
.
The second one is a bit more complex. It essentially does the following
- Create an object of type
Thing
using the constructorThing(const char*)
- Create an object of type
Thing
using the constructorThing(const Thing&)
- Call
~Thing()
on the object created in step #1
I assume with the second line you actually mean:
Thing *thing = new Thing("uiae");
which would be the standard way of creating new dynamic objects (necessary for dynamic binding and polymorphism) and storing their address to a pointer. Your code does what JaredPar described, namely creating two objects (one passed a const char*
, the other passed a const Thing&
), and then calling the destructor (~Thing()
) on the first object (the const char*
one).
By contrast, this:
Thing thing("uiae");
creates a static object which is destroyed automatically upon exiting the current scope.