The real question is not the use of pointers, but the dynamic allocation. Dynamic allocation of an object (using new ) allows you to control the lifetime of an object. If you want to create an object in a function, but do not want it to cease to exist once the function has been completed, dynamic allocation is for you.
You usually see pointers pointing to objects with dynamic allocation (since this is the best way to handle them, links are a clumsy alternative); however, you can also specify a pointer to an object with automatic storage duration:
QGridLayout mainLayout; QGridLayout* ptr = &mainLayout; ptr->addWidget(nameLabel, 0, 0); ptr->addWidget(nameLine, 0, 1); ptr->addWidget(addressLabel, 1, 0, Qt::AlignTop); ptr->addWidget(addressText, 1, 1);
^ In this example, I use automatic storage (creating the object as a "normal variable", as you put it), so the object will be destroyed at the end of the enclosing block area (perhaps the end of the function or, possibly, the conditional ( if ) block), but still using the pointer with her!
Hope this helps.
Lightness races in orbit
source share