Query: Protecting Parameters and Referencing

In BullCowGame, when we were passing FString as parameters we would only pass the reference to the FString, and also protecting the parameter from being changed by using const.

During the challenge I wondered if it was better programming to do the same thing for this function, e.g. when defining the function in the header file, could I do it as such?

void OpenDoor(const float& DeltaTime);

I thought that since DeltaTime is a float, it’s size in memory is probably not that big, so maybe using a reference is overkill, so instead I just kept it as const e.g.

void OpenDoor(const float DeltaTime);

Is this good practice to protect DeltaTime from being changed by using const, or am I overthinking this?

Anyone else had a similar thought, or can explain which way is best and why?

Basically, references are just an abstraction of pointers and fetching the value at the address would incur more overhead than copying it for small types (all primitive types would qualify as “small”).

It’s less “important” for by-value parameters as you aren’t going to affect the calling code as you have a copy and not the same object as the caller.

I honestly don’t see it that much but I would say const everything you can. The C++ Core Guidelines have an exception for const-ing them

C++ Core Guidelines

But the argument is a bit weak as it’s basically what I just said.

Other related ones:
C++ Core Guidelines
C++ Core Guidelines

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms