Return sensor data as const references rather than by value #3658
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes: #
About
This PR changes the sensor data fetch methods to return
const Output&
rather thanOutput
. This avoids a copy when the methods are being used, even in the call is like -const auto& data = getImuData()
, e.g. in ArduCopterApi.hpp, MavlinkMultiRotorApi.hpp. The copy of LidarData in particular will be more expensiveNote that a copy is still created if the method is called like -
auto data = getImuData()
How Has This Been Tested?
This is supposed to be NFC, but will try to get some testing done later or tomorrow
I wrote a simple test script to check whether copies are occurring -
test.cpp
Try playing around with this and see what happens, the behaviour before and after the PR can be tested by modifying the return type of
B::getA()
and the lineconst auto& a2 = b.getA();
Before PR:
A getA() {
,const auto& a2 = b.getA();
Output:
After PR:
const A& getA() {
,const auto& a2 = b.getA();
The
createA()
method shows the effect of Return Value Optimization, where a copy isn't made even when return type and value are bothA
rather than refs. It only kicks in if the data to be returned is to be destroyed at the end.Update:
Here's a more updated script, which more accurately reflects how things are working -
test2.cpp
a3
is a const ref,B::getA()
also returns a const ref, butgetAfromB()
returns by value, output -Change to
const A& getAfromB(B& b)
-Screenshots (if appropriate):