"Downcasting"一个std::atomic_ref<T>
"Downcasting" a std::atomic_ref<T>
是否可以在 std::atomic_ref<T>
和 std::atomic_ref<U>
之间进行向下转换,其中 U
是 T
的子类?
我尝试了以下代码,但没有用。
template<typename T>
std::atomic_ref<T> World::getComponentByID(componentInstanceId uuid) const {
static componentTypeId key = stringHash(typeid(T).name());
return components.at(uuid);
}
模板参数 T
是位置(Component
的子类)。 components
是 componentInstanceId
s 到 Component
s 的映射。
error C2440: 'return': cannot convert from 'const std::atomic_ref<Component>' to 'std::atomic_ref<Position>
这样使用atomic_ref
是没有意义的。 (即使在 lock_free
汇编语言有意义的情况下,ISO C++ 标准也不会公开该功能。)
正如@Igor Tandetnik 指出的那样,“atomic_ref 对象引用的对象的任何子对象都不能同时被任何其他 atomic_ref 对象引用。”
此规则存在的原因之一是,对于非无锁 atomic_ref
,它实现了互斥锁池,因此具有不同指针值的子对象将使您进入子对象的不同互斥锁,甚至来自不同池的互斥量,或者子对象可能是无锁的,但更大的对象是基于锁的。
此外,可能的指针调整可能会破坏对齐,atomic_ref
引用的值必须遵守 atomic_ref<T>::required_alignment
。
atomic_ref
不是通用设施。也许您只需要使用 std::mutex
或 std::shared_mutex
来保护您的对象。
是否可以在 std::atomic_ref<T>
和 std::atomic_ref<U>
之间进行向下转换,其中 U
是 T
的子类?
我尝试了以下代码,但没有用。
template<typename T>
std::atomic_ref<T> World::getComponentByID(componentInstanceId uuid) const {
static componentTypeId key = stringHash(typeid(T).name());
return components.at(uuid);
}
模板参数 T
是位置(Component
的子类)。 components
是 componentInstanceId
s 到 Component
s 的映射。
error C2440: 'return': cannot convert from 'const std::atomic_ref<Component>' to 'std::atomic_ref<Position>
这样使用atomic_ref
是没有意义的。 (即使在 lock_free
汇编语言有意义的情况下,ISO C++ 标准也不会公开该功能。)
正如@Igor Tandetnik 指出的那样,“atomic_ref 对象引用的对象的任何子对象都不能同时被任何其他 atomic_ref 对象引用。”
此规则存在的原因之一是,对于非无锁 atomic_ref
,它实现了互斥锁池,因此具有不同指针值的子对象将使您进入子对象的不同互斥锁,甚至来自不同池的互斥量,或者子对象可能是无锁的,但更大的对象是基于锁的。
此外,可能的指针调整可能会破坏对齐,atomic_ref
引用的值必须遵守 atomic_ref<T>::required_alignment
。
atomic_ref
不是通用设施。也许您只需要使用 std::mutex
或 std::shared_mutex
来保护您的对象。