1

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?

dario_ramos
  • 7,118
  • 9
  • 61
  • 108
  • 1
    `shared_ptr` has no knowledge of what you do to the object it points to. All you're guaranteed is that the shared pointer container itself works correctly even when used concurrently. – Kerrek SB Aug 24 '11 at 20:53

1 Answers1

5

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 the std::tr1::shared_ptr when it's time to delete it.

Regarding the std::tr1::shared_ptr object itself, you have the following guarantees:

  • you can safely read from the same instance from multiple threads;
  • you can safely mutate different instances of 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.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
  • What do you mean by "it guarantees mutual exclusion"? – Kerrek SB Aug 24 '11 at 20:56
  • I understood that `shared_ptr`'s data members are thread-safe, while the "foreign" data, that is, the one pointed to by the pointer passed to the `shared_ptr` constructor, is not. Am I right? – dario_ramos Aug 24 '11 at 20:58
  • @R Martinho: Hehe. In fact, my shared_ptr implementation uses those attractive atomics for the reference count. I was quite amazed by how much machinery is inside that innocent little class when I first saw it... – Kerrek SB Aug 24 '11 at 20:59
  • @dario: I added more details. – R. Martinho Fernandes Aug 24 '11 at 21:37