[英]Use a unique_ptr and return a reference or should I use a shared_ptr and make copies if needed
I have a cache that stores unique ptrs of objects in an unordered map and returns a reference of the object for users of the cache.我有一个缓存,它在无序映射中存储对象的唯一 ptr,并为缓存的用户返回对象的引用。 It works as it should, storing the objects until they go out of scope.
它可以正常工作,存储对象直到它们超出范围。
The cache is implemented as follows:缓存实现如下:
store objects in cache:在缓存中存储对象:
template<typename T>
template<typename... Args>
void ResourceCache<T>::add(const std::string& name, Args... args)
{
m_cache->try_emplace(name, std::make_unique<T>(args...));
}
get object from cache:从缓存中获取对象:
template<typename T>
T& ResourceCache<T>::getCachedElement(const std::string& name) const
{
auto it = m_cache->find(name);
if(it != m_cache->end())
return *it->second;
throw "resource not found";
}
But now I walk in to the problem that a reference is not always what I would like to get from the cache, per example:但是现在我遇到了一个问题,即引用并不总是我想从缓存中获取的,例如:
I have the following object:我有以下对象:
class GameObject
{
public:
void translate(const cheetah::Vector3f& position);
protected:
Quaternion m_rotation;
Vector3f m_position;
};
lets say I want the object to have a Texture, currently the only way for me would be to add a member reference假设我希望对象具有纹理,目前对我来说唯一的方法是添加成员引用
Texture& m_texture
This would result in me having to either这将导致我不得不要么
Now my question is现在我的问题是
What would be seen as best practice in this specific situation?在这种特定情况下,什么被视为最佳实践? should I use one of the above options or have I missed an even better option?
我应该使用上述选项之一还是错过了更好的选择?
I know my question is not the most specific but I am learning c++ by myself and it would be nice to get someone elses view on this.我知道我的问题不是最具体的,但我自己正在学习 C++,如果能得到其他人对此的看法会很好。
Assuming ResourceCache
holds Texture
, here's my thoughts.假设
ResourceCache
持有Texture
,这是我的想法。 There does not seem to be one best solution in general.一般来说,似乎没有一种最佳解决方案。
nullptr
nullptr
ResourceCache
outlives all GameObject
- the lifetimes must be managed manuallyResourceCache
所有GameObject
的寿命都长 - 必须手动管理生命周期
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.