C ++中的类的类的范围是什么? [英] What is the scope of a class inside of a class in C++?
问题描述
我写了一个类似
class Mesh {
public:
vector<Vertex> vs;
}
其中顶点
class Vertex {
public:
const double x, y, z;
}
我有一个函数加载 Mesh
从文件:
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));
}
我的问题涉及 / code>和
向量
。
一个或两个都超出范围吗?
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?
推荐答案
你的基本结构看起来很对我。您正在将顶点
复制到向量
,然后复制向量
插入 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
将向量移动到
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).
这篇关于C ++中的类的类的范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!