r/cpp • • Feb 16 '26

Favorite optimizations ??

I'd love to hear stories about people's best feats of optimization, or something small you are able to use often!

135 Upvotes

185 comments sorted by

View all comments

Show parent comment

1

u/conundorum Feb 16 '26

Usually, this pattern returns a reference to the passed object, like so:

template<typename T>
std::vector<T>& add_elem(std::vector<T>& vec, T elem) {
    vec.emplace_back(std::move(elem));
    return vec;
}

const correctness is used to indicate parameter type: const reference is assumed to be an in-parameter, non-const reference is assumed to be an out-parameter, and by-value is usually assumed to be an elision-friendly "constructed to be moved" in-parameter. (Unless you're working with C-style functions, in which case you just pray.)


This does assume that people understand const correctness well enough to instantly grok that the lack of const means the function intends to modify the parameter, so it might be best to document intent with empty IN and OUT macros, WinAPI style.

2

u/borzykot Feb 17 '26

Ok. Now tell me what this function does?

void collect_children(const node& parent, std::vector<node*>& children);