gpt4 book ai didi

c++ - 类 Vector2 最终 : shared_ptr correct or not (Updated! )

转载 作者:太空宇宙 更新时间:2023-11-04 15:48:17 25 4
gpt4 key购买 nike

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

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. 不用关心是shared_ptr还是Vector2*。因为我想标准化为一种类型

最佳答案

我不明白这如何能为您节省任何东西。为什么你的 vector 需要引用计数?对于您根本不需要的东西来说,这真的很昂贵,这会使您的代码语义复杂化,只会让读者感到 WTF。

问题不在于 vector2 是否应该 一个共享指针,或者它是否应该被包裹在一个共享指针中。没有理由这样做。

关于c++ - 类 Vector2 最终 : shared_ptr<Vector2> correct or not (Updated! ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13109850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com