These two things are very different.
QString str("my string"); creates an object whose lifetime is automatically controlled: the object either lives until the end of its covering area (if it is a local variable), or until the end of the program (if it is a global variable).
new QString("my string"); creates an object with a manually controlled lifetime, also called a "dynamic object" (and returns a pointer to this object). This means that you are responsible for managing the lifetime of the object. It is almost never worth doing if you are not writing a library component.
And here lies the essence of the C ++ philosophy: C ++ is a language for writing libraries. You have tools for writing high-quality, reusable components. If and when you do this, you will need to know the intricacies of lifecycle management. However, until the time comes, you must use existing library components. By doing so, you will find that you will hardly need to perform manual control at all.
Use dynamic containers (vectors, lines, maps, etc.) to store data and create your own data structures. Pass arguments by reference if you need to modify objects in the call area. Create complex classes from simpler components. If you really need to have dynamic objects, process them through the handler classes unique_ptr<T> or shared_ptr<T> .
Do not use pointers. Rarely use new and delete never.
(More tips: 1) Never use using namespace unless it is for ADL. 2) If you are not writing library components, well-designed classes should not have destructors, copy constructors, or assignment operators. If they do, drop the insult logic into the library component with one responsibility, see 2).)
source share