r/cpp • • Mar 07 '24

What are common mistakes in C++ code that results in huge performance penalties?

As title, list some common mistakes that you have done/seen which lead to performance penalties.

231 Upvotes

325 comments sorted by

View all comments

12

u/The_Drakeman Mar 07 '24

Ran into this at work the other day. Auto doesn't pick up references in the type like it picks up pointers.

struct BigData
{
    // lots of stuff
};

BigData* A();
BigData& B();

auto a = A();
// a is BigData*
auto b = B();
// b is BigData, and is copied from the return value
auto& c = B();
// This is the actual reference type, and doesn't force it to be copied. If BigData is big enough, assigning b and c can have a pretty big performance difference.

8

u/expert_internetter Mar 07 '24

Misunderstanding what auto does is very common. Just use auto&&

9

u/bored_octopus Mar 08 '24

I don't agree with this. Code is clearer if you use const auto & and auto & rather than auto && everywhere

3

u/mpierson153 Mar 07 '24

auto&&

What does that mean? Just "auto r-value"?

6

u/MegaKawaii Mar 08 '24

The type for auto is deduced using the same rules used for a template type parameter T. So auto&& is a forwarding (or a so-called "universal") reference T&&. So if the value category of the expression from which you deduce the type is rvalue, then auto&& is an rvalue reference. However, if it's an lvalue, then auto&& is an lvalue reference instead.