Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recommended way of returning pointer from C++ function?

Tags:

c++

pointers

I have a pointer that is passed to a series of functions, where one function returns an address and assigns that address to the pointer. After seeking some help on Stackoverflow, the collect_file_path method has a parameter of type QStringList**. Although I understand what is going on I have not come across this notation in any of the text books I own, plus, it looks ugly.

I would like some advice/feedback on how other programmers would implement what I have done in the code below. Would you use QStringList**, or some other method?

I hope what I'm asking makes sense. My current code is:

void ThreadWorker::run()
{
  QStringList* file_list;
  collect_file_paths(&file_list);
}

void ThreadWorker::collect_file_paths(QStringList** file_list)
{
  DirectorySearch ds;
  *file_list = ds.get_file_names(_strPath);
}

QStringList* DirectorySearch::get_file_names(QString path)
{
  QStringList *file_names = new QStringList;
  traverse(path, file_names);
  return file_names;
}

Thanks

like image 696
nf313743 Avatar asked Jan 19 '23 10:01

nf313743


1 Answers

The problem with returning a bare pointer is that it's quite easy to end up leaking the memory for the object. This might happen for example if anything in your function throws; but it can also happen on the caller's side, before they have received the pointer (e.g. if it is used as an argument to a function, and the evaluation of another argument throws).

For these reasons, it's best to wrap pointers in a smart pointer like std::auto_ptr (unique_ptr in the upcoming C++ standard) or boost::shared_ptr (also available as std::shared_ptr, soon in a standard library near you). These wrappers will safely take care of deleting the wrapped pointer when the time comes to do so.

However, in this specific case you can manage without using a QStringList** by passing the QStringList* as a reference.

like image 185
Jon Avatar answered Jan 31 '23 13:01

Jon