I've written a class that looks like
class Mesh {
public:
vector<Vertex> vs;
}
where Vertex
is
class Vertex {
public:
const double x, y, z;
}
I have a function which loads a Mesh
from a file:
shared_ptr<Mesh> load_mesh(string filename) {
//....
vector<Vertex> vs;
Vertex v(1, 2, 3);
vs.push_back(v);
return shared_ptr<Mesh>(Mesh(vs));
}
My questions are concerning the scope of the Vertex
and the vector
.
Will one or both go out of scope?
Which (if any) of the alternatives are preferred?
class Mesh1 {
public:
vector<shared_ptr<Vertex>> vs;
}
class Mesh2 {
public:
shared_ptr<vector<Vertex>> vs;
}
class Mesh3 {
public:
shared_ptr<vector<shared_ptr<Vertex>>> vs;
}
Or is there a better / easier way of handling this?
Your basic structure looks right to me. You are copying the
Vertex
into thevector
and then copying thevector
into theMesh
. The local copies in theload_mesh()
function will go out of scope but because you have made a copy that is ok.At the risk of being accused of premature optimization I would say that unless the
vector
is small all that copying is a little inefficient. There are a number of ways it could be optimized. With C++11, and move semantics, you can keep your current structure and just move the data:I'm using
emplace_back
instead ofpush_back
to construct theVertex
in thevector
in-place and usingstd::move
to move thevector
intoMesh
.Returning a
shared_ptr<Mesh>
would be fine but I wanted to show you can also return theMesh
by value. The compiler should perform RVO and there will be no copy (see this question).