What's better? Return a list of object pointers? or Return a pointer to list of objects?

537 views Asked by At

I have a code that read Products from database and return them as a list.

std::list<Product> findAll() {...}

The code above (CRUD) is part of a library (third party library). Client code get the list and pass it over 3 layers (MVC). I know this process copy the list on every call.

I want to improve this process and the questions are: Getting the list

  • Should I create a list of Product pointers and return it.std::list<Product*> products;
  • Or should I create a pointer to list of Products and return it. std::list<Product> *productsPtr;

What's more efficient? Return a list of Product pointers or return a pointer to a list. I know that modern compilers have RVO. How can I use that feature?. Because, I'm using clang-v5.0.0 and sending outputs to screen I saw that products are created and destroyed every time (copy).

And some questions more. What's better?:

  • A library should return a list of Product objects (current state)? or a list of Product pointers (smart pointers) or receive a list reference as parameter?
  • Product class must implement move constructors to guarantee RVO?

More info.

  • Product class has default constructor. Its info (id, name, price, etc.) are filled by setters and getters.
  • The list is mainly used to be shown on tables. However the list must pass from library to Model, then to Controller and finally to View. The view allows add, update and delete Products. That's the reason of my question.
  • I like the idea to use std::vector because improve data access.

But my principal doubts here is: return a container (list, vector, etc) of Plain Objects or pointers or a pointer to container?.

1

There are 1 answers

0
Michael On

If you are using C++11 or higher (which you should), returning std::list<Product> is the better option, since no copy will take place.

If you are using an older C++, you should probably pass an out parameter std::list<Product>&. Using a list of pointers is neither effecient nor comfortable, and it will invoke the copy on the pointers as well - it might be better than copying the whole product but it is still an unnecessary copy.

By the way, if effeciency bothers you, you should probably use a vector (unless you are sure you don't need to).

About RVO (C++11 or higher) - if you return a non-const object from a function, it uses its move constructor instead of copying the data. There is a concept of copy elision - if you return a newly-constructed

For example:

return std::vector{1,2,3,4,5};

The compiler will construct the object in-place for the returned value.

Note - copy elision is part of the standardemphasized text as for C++17.