我有一个类,其中包含一个 BYTE*、一个引用计数器和一个 CRITICAL_SECTION,它可以保护它们免受并发访问。
我想用 std::tr1::shared_ptr
替换所有这些。 MSDN 说:
多个线程可以读写不同的shared_ptr对象
同时,即使对象是共享所有权的副本。
一切听起来都不错,直到我发现类中的 CRITICAL_SECTION
在类外部使用来“锁定”它并以互斥的方式更改其内容。好吧,这破坏了封装,我想改变它。
我知道shared_ptr
保证内存将被释放,但是当你写入内存时它能保证互斥吗?
I have a class which contains a BYTE*
, a reference counter and a CRITICAL_SECTION
which protects both of them from concurrent access.
I wanna replace all that with a std::tr1::shared_ptr<BYTE>
. The MSDN says that:
Multiple threads can read and write different shared_ptr objects at
the same time, even when the objects are copies that share ownership.
Everything sounds alright, until I find out that the CRITICAL_SECTION
from the class is used outside of it to "lock" it and alter its contents in a mutually exclusive fashion. Okay, it's breaks encapsulation, I wanna change that.
I know shared_ptr
guarantees that the memory will be freed, but does it guarantee mutual exclusion when you write to the memory?
发布评论
评论(1)
您需要确保正确访问
std::tr1::shared_ptr
指向的数据。该数据是您的。仅当需要删除 std::tr1::shared_ptr 时,它才有意义。关于 std::tr1::shared_ptr 对象本身,您有以下保证:
shared_ptr
的不同实例,即使实例是副本(共享相同的引用计数或其他);任何其他同时访问(例如同时读取和写入同一实例)都是未定义的行为。
另请注意,新 C++11 标准中的
shared_ptr
有一个用于原子访问的特殊 API。It is up to you to ensure correct access to the data the
std::tr1::shared_ptr
points to. That data is yours. It only matters to thestd::tr1::shared_ptr
when it's time to delete it.Regarding the
std::tr1::shared_ptr
object itself, you have the following guarantees:shared_ptr
from multiple threads, even when the instances are copies (sharing the same reference count or whatever);Any other simultaneous access (like reading and writing simultaneously to the same instance) is undefined behaviour.
Also note that the
shared_ptr
in the new C++11 standard has a special API for atomic access.