使用智能或原始指针 [英] Use smart or raw pointer
问题描述
在下面的代码中,有一个 Grid
,其中包含 points
。同样,元素
和 Face
也有点
指向网格
中的分
。
In the code below, there is a Grid
which contains points
. Likewise, Element
and Face
also have points
but I want to them to point to points
in Grid
.
我应该使用智能或原始指针。如果我使用智能指针应该使用 std :: unique_ptr
或 std :: shared_ptr
?
Should I use smart or raw pointers. If I use smart pointers should I use std::unique_ptr
or std::shared_ptr
?
struct Vector3
{
vector <double> dim;
Vector3 ()
{
dim.resize(3);
}
};
struct Element
{
vector <Vector3*> points;
};
struct Face
{
vector <Vector3*> points;
};
struct Grid
{
vector <Vector3> points;
vector <Element> elms;
vector <Face> faces;
};
推荐答案
在这里,您指定前提条件是元素
对象在
Grid
对象中创建,容器的元素引用相同的 Grid
容器,因此所有三个容器的生命周期(点
, elms
和<$
Here you specified that the precondition is that Element
and Face
objects are created in a Grid
object with the elements of the container referring to the same Grid
containers, therefore the lifetime of all three containers (points
, elms
and faces
) is the same.
现在你必须考虑两种情况。
Now you have to consider two cases.
在这种情况下, code>保证从不使对其元素的引用无效(例如,它从不被修改)。这里你不需要任何智能指针,你可以使用一个简单的
std :: reference_wrapper
如下:
struct Vector3
{
std::vector<double> dim;
Vector3 () : dim(3) {}
};
template<class Type>
using ref_vec = std::vector<std::reference_wrapper<Type>>;
struct Element { ref_vec<Vector3> points; };
struct Face { ref_vec<Vector3> points; };
struct Grid
{
std::vector<Vector3> points;
std::vector<Element> elms;
std::vector<Face> faces;
};
另一个解决方案,不等同于您的示例( elms
和 faces
无法直接访问 Vector3
对象)可能使用索引:
Another solution, non equivalent to your example (elms
and faces
don't have direct access to the Vector3
object) might be to use indexes:
struct Vector3
{
std::vector<double> dim;
Vector3 () : dim(3) {}
};
struct Grid
{
struct Element { std::size_t point_indices; };
struct Face { std::size_t point_indices; };
std::vector<Vector3> points;
std::vector<Element> elms;
std::vector<Face> faces;
};
也就是说,您存储的索引 points
。
That is, you store the indices of points
.
在 points
上执行可能使引用无效,那么您可能需要考虑另一个不会使元素的引用/指针/迭代器无效的容器。
If the operations performed on points
can invalidate references, then you might want to consider another container that does not invalidate references/pointers/iterators to the element.
例如 std :: deque
保证在容器开头和末尾删除/插入引用的有效性。
For example std::deque
guarantees the validity of references for deletion/insertion at the beginning and end of the container.
一旦你选择了正确的容器,你可以只应用上面相同的想法。
Once you have chosen the correct container you can just apply the same ideas as above.
这篇关于使用智能或原始指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!