Fix a subtle reference cycle that can lead to increased memory consumption.

Closes #1165.