I'd like to return an Eigen::Vector from a function and wondering what's the proper way to do it. Something like
Eigen::VectorXd& getMesh(int N) {
Eigen::VectorXd mesh(N + 1); // nb. of nodes
// Nodes are equally spaced
for (int i = 0; i < N + 1; i++) {
mesh[i] = i * (1.0 / N);
}
return mesh;
}
int main() {
// Mesh with 100 cells
Eigen::VectorXd mesh = getMesh(100);
return 0;
}
Now of course, we might get into problems here since the memory used to create the mesh vector in getMesh() might not be dynamically allocated i.e. when we return from the function, out reference "points" to deleted memory.
I could allocate the memory inside the main function and then pass it to the getMesh function, but is that considered fine? What other possibilities would I have?