类 Vector2 最终:shared_ptr<Vector2>正确与否(更新!

class Vector2 final : shared_ptr<Vector2> correct or not (Updated!)

本文关键字:Vector2 更新 lt 最终 shared ptr gt      更新时间:2023-10-16

这样做的原因是,我想在使用此类时强迫所有对象成为智能指针。因此,我可以保存一些代码,例如

class Vector2 final : shared_ptr<Vector2>
{
...
inline shared_ptr<Vector2> getVector2(); //--> inline Vector2 getVector2();
...
inline static float dot(const shared_ptr<Vector2> a, const shared_ptr<Vector2> b); //--> inline static float dot(const Vector2 a, Vector2 b);
}

正确吗?如果是,这是最好的做法吗?如果没有,最好的是什么?

==========================================================================================

也许我使用另一个示例

class Sprite
{
private:
Vector2* pPosition;
shared_ptr<Vector2> position;
Image* pBackground;
shared_ptr<Image> background;
};

让我解释为什么我需要参考计数。当我更新位置或背景时,我需要在分配新值之前处理删除操作。

这个

怎么样
inline static shared_ptr<Vector2> add(const Vector2* a, const Vector2* b)

这将返回在退出功能之前可能会或可能不会使用的结果。然后,如果不使用它,我需要手动删除。

代码保存是指1.无需手动删除对象2.不需要关心它是共享_ptr还是vector2*。因为我想标准化为一种类型

我不明白如何为您节省任何东西。为什么您的矢量根本需要被参考?对于您从根本上不需要的东西来说,这确实很昂贵,这使您的代码语义变得复杂,并且只会使读者变得WTF。

问题不是vector2是否应该是共享指针,或者是否应该将其包裹在共享指针中。没有理由做。

我认为您的设计非常糟糕。好像您想拥有Java寿命或其他东西。

您需要考虑到关注点的分开设计。

您的功能dot不应关心如何管理向量的寿命2,只需通过参考将vector2对象插入,然后将它们包裹在 std::shared_ptr s中,然后在使用之前将其fefreference defreference。

在同一徒劳中,您的vector2对象不应对如何管理其生命周期。