I am very concerned about performance and readability of the code and I get most of my ideas from Chandler Carruth from Google. I would like to apply the following rules for C++ for clean code without loosing performance at all.
- Pass all POD as values
- Pass all objects that you don't want to mutate by const reference
- Pass all objects that your function needs to consume by value
- Ban everything else. When in corner cases, pass a pointer.
That way, functions don't have side effects. That's a must for code readability and makes C++ kind of functionnal. Now comes performance. What can you do if you want to write a function that adds 1 to every element of a std::vector? Here is my solution.
std::vector<int> add_one(std::vector<int> v) {
...what you expect...
}
...
v = add_one(std::move(v));
...
I find this very elegant and makes only 2 moves. Here are my questions:
- Is it legal C++11 ?
- Do you think of any drawback with this design?
- Couldn't a compiler automatically transform v = f(v) into this? A kind of copy elision.
Aucun commentaire:
Enregistrer un commentaire