4

This is about the source code of the statistical machine translation system Moses. In the Factor class of the Mosesdecoder project, there is this strange use of the keyword mutable:

class Factor {

    __SOME_OTHER_CODE__

    // FactorCollection writes here.
    // This is mutable so the pointer can be changed to pool-backed memory.
    mutable StringPiece m_string
    size_t m_id;

    __SOME_OTHER_CODE__
}

The complete file of Factor.h is here. I know that mutable is used when you want to modify a member variant in a const member function, or when you want to modify some out-of-scope variable in a lambda expression. I do not, however, understand what the mutable is doing in this code.

I appreciate any hint. Thank you.

Yuhuan Jiang
  • 2,616
  • 2
  • 19
  • 21

1 Answers1

4

You've provided little enough information that about all we can do is guess.

That said, from the comment, it sounds like they have some sort of storage pool, and they may want to move the storage for the string into the storage pool. Like most uses of mutable, it's to deal with a bitwise modification that still leaves the object logically un-modified (i.e., they change a pointer so it points to the same data, but at a different address).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • Thank you for this quick reply. This `m_string` thing is modified by another class. I usually see a member function modify a member variable marked by `mutable` in the same class. That's why I feel strange. – Yuhuan Jiang Dec 16 '13 at 07:03
  • @YuhuanJiang: if it's a "pool", there may well be some kind of pool manager that "reaches in" to modify `m_string`: for example - if the pool's deallocated it might set `m_string` to be empty, or to throw an exception the next time it's accessed. You're not giving much information about what you've seen, what you expected, and why the difference is confusing. – Tony Delroy Dec 16 '13 at 07:21
  • @YuhuanJiang: The main purpose of `mutable` is to allow modifying the mutable fields of an object even through a `const` reference or pointer. This is generally safe so long as the object remains _logically_ constant. For example, if the string held by `m_string` doesn't change, it doesn't matter if the internal representation of `m_string` changes. By outward appearances, `m_string` has remained constant. In this example, it appears some memory management code might want to move where the string's text is stored without changing that text. That's "logically const." – Joe Z Dec 16 '13 at 07:26