What is the scope of a class inside of a class in

2019-08-22 06:44发布

问题:

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?

回答1:

Your basic structure looks right to me. You are copying the Vertex into the vector and then copying the vector into the Mesh. The local copies in the load_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:

#include <vector>

struct Vertex {
  const double x, y, z;
  Vertex(double _x, double _y, double _z) : x(_x), y(_y), z(_z) {} 
};

struct Mesh {
  std::vector<Vertex> vs;
  Mesh(std::vector<Vertex> _vs) : vs(std::move(_vs)) {}
  Mesh(Mesh&& other) noexcept : vs(std::move(other.vs)) {}  // Move constructor
};

Mesh
loadMesh() {
  //....
  std::vector<Vertex> vs;
  vs.emplace_back(1,2,3);
  return Mesh{std::move(vs)};
}

int main() {
  auto mesh = loadMesh();
}

I'm using emplace_back instead of push_back to construct the Vertex in the vector in-place and using std::move to move the vector into Mesh.

Returning a shared_ptr<Mesh> would be fine but I wanted to show you can also return the Mesh by value. The compiler should perform RVO and there will be no copy (see this question).



标签: c++ scope