简体   繁体   中英

Should I use a pointer when dealing with lists?

Pointers should be used when an object should live longer, even when it goes out of scope, right?

Here I just create a Movie m; . It will be created on the stack and automatically deleted when it goes out of scope.

//In some header file
typedef struct{
Qstring name;
int id;
//...
} Movie ;


QList<Movie> movieList; //It's the same as the standard list of c++. 

//In a function somewhere else
void doSomething(/*...*/)
{
//Do something...
Movie m = { /* ... */ };
movieList.push_back( m );
}

A list takes a constant reference of type T as argument. So it's the address, right? But when Movie m; goes out of scope it will be deleted. Somehow the item in the list stays.

However, my question is should I use a pointer and create the Movie m; on the heap or is this fine? What is better style?

"Pointers should be used when an object should live longer, even when it goes out of scope, right?"

Although it is true that local objects with automatic storage duration are automatically destructed when the execution goes out of scope, it does not necessarily mean that dynamically allocated object would live longer.

In your application, you have global variable:

QList<Movie> movieList;

representing container that lives during the whole time of your program's execution.

"Somehow the item in the list stays"

When you create an object of type Movie and push it into your container:

Movie m;
...
movieList.push_back(m);

the copy of this object is stored in the list. Copies are being created in different situations, mainly when you pass or return by value, yet in most of cases it will have no negative impact on performance of your program. There are many optimization techniques that your compiler will use to elide copies... sometimes so effectively that passing/returning by value might become even faster than passing by reference.

" should I use a pointer and create the Movie m; on the heap? "

NO! Once you start allocating objects dynamically, you take the responsibility for memory management on yourself and many things might become far more complicated that they could be otherwise... including possible and very frequent (usually due to imperfections in error handling) problems with memory leaks , problems with dangling pointers that might make you fall into the pits of undefined behavior and many other kinds of unpleasant stuff.

Avoid dynamic memory allocation always when it is possible. Use objects with automatic storage duration, learn about RAII idiom and take delight in following it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM