在 C++ 中——是否可以将 volatile shared_ptr 与 nullptr 进行比较?
In C++ - is it possible to compare volatile shared_ptr to nullptr?
shared_ptr
实现中的 volatile
比较函数似乎不存在。
它的存在还有意义吗?
Volatile 只是向编译器指示内存可能会意外更改。关闭一些优化。在幕后它只是一个内存地址。
共享指针就是holding/managing资源。也就是说,由于 std::shared_ptr::get() 未标记为易失性,因此您不能真正使用 shared_ptr 以可访问的方式管理易失性指针。
我建议使用裸指针,并使用作用域退出或析构函数在它之后进行清理。
如果您使用 volatile 因为指针可能会被另一个线程修改,您可能需要考虑使用 std::atomic 而不是 volatile。在线程工作流中,在 std::atomic 之前,从其他线程访问的指针通常被标记为易变的。这不再是最佳实践。
基本上不,该标准不适合 volatile shared_ptr
.
上的 comparisons or boolean conversion
following fails编译...
auto main() -> int {
volatile shared_ptr<int> a;
if (a == nullptr) // fails
; // empty
if (a) // fails
; // empty
}
您可以关闭 volatile
(通过 a const_cast
),但我不确定这是否会产生预期的结果。来自 cppreference:
Modifying a const
object through a non-const
access path and referring to a volatile
object through a non-volatile
glvalue result in undefined behavior.
更一般地说,在不将成员方法标记为 volatile
时,class 或库实现者实际上是在说 "this is not intended to be use as a volatile
object" - 如果是,则适当的方法或重载将提供 volatile
个对象。同样,这适用于 const
,在将成员标记为 const
时,他们说“这个 class 可以用作 const
对象。
为什么需要 volatile
,哪些外部资源可以修改 shared_ptr
"without the knowledge of the compiler"(这是 volatile
的用途之一)?如果存在线程问题,那么您最好使用线程库实用程序之一,或者如果要求只是关闭优化,各种编译器已经有这种机制(pragmas 等)。
shared_ptr
实现中的 volatile
比较函数似乎不存在。
它的存在还有意义吗?
Volatile 只是向编译器指示内存可能会意外更改。关闭一些优化。在幕后它只是一个内存地址。
共享指针就是holding/managing资源。也就是说,由于 std::shared_ptr::get() 未标记为易失性,因此您不能真正使用 shared_ptr 以可访问的方式管理易失性指针。
我建议使用裸指针,并使用作用域退出或析构函数在它之后进行清理。
如果您使用 volatile 因为指针可能会被另一个线程修改,您可能需要考虑使用 std::atomic 而不是 volatile。在线程工作流中,在 std::atomic 之前,从其他线程访问的指针通常被标记为易变的。这不再是最佳实践。
基本上不,该标准不适合 volatile shared_ptr
.
following fails编译...
auto main() -> int {
volatile shared_ptr<int> a;
if (a == nullptr) // fails
; // empty
if (a) // fails
; // empty
}
您可以关闭 volatile
(通过 a const_cast
),但我不确定这是否会产生预期的结果。来自 cppreference:
Modifying a
const
object through a non-const
access path and referring to avolatile
object through a non-volatile
glvalue result in undefined behavior.
更一般地说,在不将成员方法标记为 volatile
时,class 或库实现者实际上是在说 "this is not intended to be use as a volatile
object" - 如果是,则适当的方法或重载将提供 volatile
个对象。同样,这适用于 const
,在将成员标记为 const
时,他们说“这个 class 可以用作 const
对象。
为什么需要 volatile
,哪些外部资源可以修改 shared_ptr
"without the knowledge of the compiler"(这是 volatile
的用途之一)?如果存在线程问题,那么您最好使用线程库实用程序之一,或者如果要求只是关闭优化,各种编译器已经有这种机制(pragmas 等)。