且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++中的类的类的范围是什么?

更新时间:2023-01-14 08:32:49

你的基本结构看起来很对我。您正在将顶点复制到向量,然后复制向量插入 Mesh load_mesh()函数中的本地副本将超出范围,但因为您创建的副本是确定的。

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.

有被指控过早优化的风险,我会说,除非向量是小的所有复制是有点低效率。有很多方法可以优化。使用C ++ 11和移动语义,您可以保留当前结构,并移动数据:

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();
}

我使用 emplace_back 而不是 push_back 来构造向量中的顶点 >使用 std :: move 向量$ c>移动到 code>。

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.

返回 shared_ptr< Mesh> 会很好,但我想告诉你也可以返回 Mesh 。编译器执行 RVO ,且不会有副本(请参阅此问题)。

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).