You can return by value, as unnecessary copies will be optimized. This is a clear, safe exception, and my recommended way.
void ThreadWorker::run() { QStringList file_list = collect_file_paths(); } QStringList ThreadWorker::collect_file_paths() { DirectorySearch ds; return ds.get_file_names(strPath_); // you should not use leading underscore in c++ } QStringList DirectorySearch::get_file_names(QString path) { QStringList file_names; traverse(path, &file_names); return file_names; }
http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
Btw. I think Qt Containers has a copy for recording optimization, so the copy will be cheap even without compiler optimization.
If you do not trust the (very common) compiler optimizations, such as RVO (heishe comment), and you do not use copy-on-write objects such as QStringList, you must create an instance in the run () method and pass a link to other functions. This is not as clear as my recommended technique, but it is still an exception (at least a basic guarantee).
void ThreadWorker::run() { QStringList file_list; collect_file_paths(file_list); } void ThreadWorker::collect_file_paths(QStringList& file_list) { DirectorySearch ds; ds.get_file_names(strPath_, file_list); } void DirectorySearch::get_file_names(QString path, QStringList& file_list) { traverse(path, &file_list); }
The third solution is to return a smart pointer, for example std::unique_ptr<QStringList> . But I see no reason for additional dynamic allocation in this example.
source share