Reputation: 75
Given the following vector and functions:
std::vector<int> param;
std::vector<int>& getparam_1() {
return param;
}
std::vector<int> getparam_2() {
return param;
}
I understand that both following expressions will be compiled:
std::vector<int> param_copy1 = getparam_1();
std::vector<int> param_copy2 = getparam_2();
But what are their differences?
Upvotes: 1
Views: 418
Reputation: 197
The most obvious difference is you can change the global variable if you return by reference.
EXAMPLE
#include <iostream>
#include <vector>
std::vector<int> param{ 1,2,3,4,5 };
std::vector<int>& getparam_1()
{
return param;
}
std::vector<int> getparam_2()
{
return param;
}
int main()
{
getparam_1().push_back(9);
for (const auto& i : param)
{
std::cout << i;
}
}
This will print "123459".
#include <iostream>
#include <vector>
std::vector<int> param{ 1,2,3,4,5 };
std::vector<int>& getparam_1()
{
return param;
}
std::vector<int> getparam_2()
{
return param;
}
int main()
{
getparam_2().push_back(9);
for (const auto& i : param)
{
std::cout << i;
}
}
This will print "12345".
Upvotes: 2
Reputation:
Return by value
Copy of that value is returned to the caller.
Return by reference
Reference to the variable is passed back to the caller. The caller can then use this reference to continue modifying the vector.
If you are using int
in the vector you do not have to bother return by reference
it does not make big different. If you are using class or struct you should take consideration of using return by reference or pointer.
Upvotes: 1
Reputation: 238311
But what are their differences?
The outcome is identical, so there is no difference in that regard.
From perspective of the abstract machine, prior to C++17, both examples have one copy and the second example has a move from that copy. But the move can be optimised away, so there's still no practical difference necessarily. Since C++17, there is just one copy and no move in either case.
There is minor difference for the abstract machine in where that copy happens. In first example the copy is outside the function while in the second example the copy is inside the function.
Upvotes: 1