Making types immutable is often desireable, especially for multi-threaded applications. There's no need to worry about concurrent access and no need for any synchronization. The common STL containers require the contained objects to be assignable, however, so they don't work with immutable types.

How should I strike a balance between wanting immutable types and wanting STL-compatible types? What I could:

  • provide an assignment operator and stop worrying about immutability. Either add synchronization or document that object assignment isn't thread-safe.
  • live with the fact that the types can't go directly into containers and wrap them in std::unique_ptr/std::shared_ptr when required.

What are the tradeoffs involved and which solution should I prefer for what types of objects? Should I strive to always make my objects STL compatible or should I only do that when I anticipate need for it? Should I strive to always make my objects immutable or only when I see concrete benefit from it?

  • Are you even writing multi-threaded code to begin with? – whatsisname May 13 '15 at 16:11
  • I'm interested in the general design tradeoff. But yes, the question arose while adding multi-threaded processing to a previously single-threaded app, and noticing that it was remarkably easy because the key objects were immutable data producers. – Christian Aichinger May 13 '15 at 17:49
up vote 3 down vote accepted

Typical C++ is more about values that are copied than about making immutable objects that are shared. Separation instead of immutability. Try to keep the different threads' data separate.

If you do want immutable shared data, you can always make a shared_ptr<T>, fill the object there with data, then hand out shared_ptr<const T> references to it. Or use something like Adobe's copy_on_write.

So make your classes mutable and have them behave as proper values.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.