Reputation: 1071
I have the following function
std::pair<Eigen::ArrayXXd, Eigen::VectorXd> f(...){
...
auto a = Eigen::ArrayXXd(N,M);
auto b = Eigen::VectorXd(M);
...
return {std::move(a), std::move(b)};
}
int main() {
...
const auto &[a_up, b_up] = f(...);
writeToFile("b_up.txt", b_up);
...
}
In the Function f
we allocate and initialize the Eigen Array and Vector a
and b
. With the move
-keyword we still use the same memory that was allocated inside the function f
. With const auto & b_up = f(...)
also outside the function f
the same memory space is used, so we never had to copy anything. Is this correct? But what is the advantage over Pass-by-reference. Does there copying happen?
Upvotes: 0
Views: 96
Reputation: 5887
The return
statement in f
function creates std::pair
witch is not copied further, due to RVO, even if you write:
auto ab_pair = f(...);
But still the a
and b
have to be moved or copied, but there is a way to construct that pair in place using std::piecewise_construct
and then return it by reference with RVO:
auto f(...){
std::pair<Eigen::ArrayXXd, Eigen::VectorXd> result{
std::piecewise_construct,
std::make_tuple(N,M),
std::make_tuple(M),
};
...
return result;
}
Upvotes: 2